﻿using Dapper;
using Estsh.Core.Base;
using Estsh.Core.Dapper;
using Estsh.Core.Wms.IRepositories;
using Estsh.Core.Model.Result;
using Estsh.Core.Repositories;
using System.Collections;
using System.Data;
using System.Text;
using System.Security.Cryptography;
using System.Text.Json;
using Estsh.Core.Models;
using Newtonsoft.Json.Linq;
using Estsh.Core.Model.EnumUtil;
using System.Data.Common;
using System.Text.RegularExpressions;
using NPOI.SS.Formula.Functions;
using static NPOI.HSSF.Util.HSSFColor;
using Estsh.Core.Model.Extend.EnumUtil;
using Estsh.Core.Model.Extend.Models;
using Microsoft.Extensions.Primitives;
using System;

namespace Estsh.Core.Wms.Repositories
{
    public class ReceiveRepository : BaseRepository<BaseEntity>, IReceiveRepository
    {
        public ReceiveRepository(DapperDbContext _dapperDbContext) : base(_dapperDbContext)
        {

        }
        /// <summary>
        /// 正常收货
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <param name="isRejection"></param>
        /// <param name="groupNo"></param>
        /// <returns></returns>
        public string CheckCartonStatus(string cartonNo, bool isRejection, string groupNo, string loginId, string supportingParts, string cdNum, string orderNo, bool isQc)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                string result = string.Empty;

                StringBuilder sql = new StringBuilder(1024);
                if (orderNo != "")
                    sql.Append("select * from sys_stock (nolock) where ref_order_no=@orderNo ");
                else
                    sql.Append("select * from sys_stock (nolock) where ref_order_no in ( select ref_order_no from sys_stock (nolock) where carton_no=@carton_no) ");
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@orderNo", orderNo);
                parameters.Add("@carton_no", cartonNo);
                List<SysStock> dt = dbConn.Query<SysStock>(sql.ToString(), parameters).ToList();

                if (dt.Count > 0)
                {
                    List<SysStock> sysStocks = dt.Where(a => a.CartonNo == cartonNo).ToList();

                    if (sysStocks.Count > 0)
                    {
                        if (sysStocks[0].Enabled == "N")
                        {
                            return " [" + cartonNo + "] : 包装条码已被冻结!";
                        }
                        if (sysStocks[0].Status == (int)WmsEnumUtil.StockStatus.WAITING_RECEIVE)
                        {
                            if (isRejection)
                            {
                                return "OK";
                            }
                            if (isQc && cdNum == "")
                            {
                                return "OK" + Convert.ToInt32(sysStocks[0].Qty);
                            }
                            if (isQc && cdNum != "" && !isRejection)
                            {
                                sysStocks[0].Qty = Convert.ToInt32(cdNum);
                            }


                            //获取收货库位信息
                            StringBuilder receiveLocate = new StringBuilder(1024);
                            receiveLocate.Append("SELECT * FROM dbo.sys_locate (nolock) WHERE locate_type =@locate_type ");
                            DynamicParameters receiveLocateparameters = new DynamicParameters();
                            receiveLocateparameters.Add("@locate_type", (int)WmsEnumUtil.LocateType.COLLECT_LOCATE);
							List<SysLocate> SysLocate = dbConn.Query<SysLocate>(receiveLocate.ToString(), receiveLocateparameters).ToList();

                           
							int locateId = 0;
                            string locateName = string.Empty;
                            int warehouseId = 0;
                            string warehouseName = string.Empty;
                            int zoneId = 0;
                            string zoneName = string.Empty;

                            if (SysLocate.Count == 0)
                            {
                                //无收货库位 
                            }
                            else
                            {
                                locateId = SysLocate[0].LocateId;
                                locateName = SysLocate[0].LocateName;
                                warehouseId = SysLocate[0].WarehouseId;
                                warehouseName = SysLocate[0].WarehouseName;
                                zoneId = SysLocate[0].ZoneId;
                                zoneName = SysLocate[0].ZoneName;
                            }

                            List<string> sqlStrings = new List<string>();
                            List<DynamicParameters> parameterList = new List<DynamicParameters>();


                            //更新收货主表状态：收货中
                            StringBuilder updateString2 = new StringBuilder(1024);
                            updateString2.Append("update wms_purchase set order_status='30',update_userid=@update_userid,update_time=@update_time where order_no=@order_no  ");
                            DynamicParameters updateStringparameters2 = new DynamicParameters();
                            updateStringparameters2.Add("@order_no", sysStocks[0].RefOrderNo);
                            updateStringparameters2.Add("@update_userid", loginId);
                            updateStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            sqlStrings.Add(updateString2.ToString());
                            parameterList.Add(updateStringparameters2);

                            //                            StringBuilder getRealDetail = new StringBuilder(1024);
                            //                            getRealDetail.Append(@"select a.order_no,a.part_id,a.part_no,a.part_spec,b.qty,b.boxqty,isnull(c.recqty,0) recqty,isnull(c.recboxqty,0) recboxqty,a.enabled  from wms_purchase_detail as a 
                            //left join (select part_id,sum(qty) qty,count(1) as boxQty from sys_stock where ref_order_no=@order_no and enabled='Y'  group by part_id ) as b on a.part_id = b.part_id
                            //left join (select part_id,sum(qty) recQty,count(1) as recBoxQty from sys_stock where ref_order_no=@order_no and enabled='Y' and status not in (@status20,@status150) group by part_id ) as c on a.part_id=c.part_id
                            //where a.order_no=@order_no and a.enabled='Y' order by cast( a.item_no as int)");
                            //                            DynamicParameters getRealDetailparameters = new DynamicParameters();
                            //                            getRealDetailparameters.Add("@order_no", sysStocks[0].RefOrderNo);
                            //                            getRealDetailparameters.Add("@status20", (int)WmsEnumUtil.StockStatus.WAITING_RECEIVE);
                            //                            getRealDetailparameters.Add("@status150", (int)WmsEnumUtil.StockStatus.REJECTION);
                            //                            //通过扫描箱条码，获取对应收货订单
                            //                            List<WmsPurchaseDetail> getRealDetails = dbConn.Query<WmsPurchaseDetail>(getRealDetail.ToString(), getRealDetailparameters).ToList();

                            //                            //更新收货明细表：实收数  更新状态：收货中
                            //                            StringBuilder updateString3 = new StringBuilder(1024);
                            //                            updateString3.Append("update wms_purchase_detail set  item_status=(CASE WHEN  qty <= rec_qty + @rec_qty THEN '40' ELSE '30' end)," +
                            //                                "rec_qty = (CASE WHEN  qty <= rec_qty + @rec_qty THEN qty ELSE rec_qty + @rec_qty end)," +
                            //                                "rec_box_qty= (CASE WHEN  box_qty <= rec_box_qty + 1 THEN box_qty ELSE  rec_box_qty + 1 end)  ," +
                            //                                "update_userid=@update_userid,update_time=@update_time where order_no=@order_no and part_id=@part_id");
                            //                            DynamicParameters updateStringparameters3 = new DynamicParameters();
                            //                            updateStringparameters3.Add("@order_no", sysStocks[0].RefOrderNo);
                            //                            updateStringparameters3.Add("@rec_qty", sysStocks[0].Qty);
                            //                            updateStringparameters3.Add("@part_id", sysStocks[0].PartId);
                            //                            updateStringparameters3.Add("@update_userid", loginId);
                            //                            updateStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            //                            sqlStrings.Add(updateString3.ToString());
                            //                            parameterList.Add(updateStringparameters3);

                            //更改条码表状态
                            StringBuilder updateString = new StringBuilder(1024);
                            updateString.Append("update sys_stock set status='25',group_no=@group_no,qty=@qty,update_userid=@update_userid,update_time=@update_time,locate_id=@locate_id,locate_name=@locate_name,warehouse_id=@warehouse_id,warehouse_name=@warehouse_name,zone_id=@zone_id,zone_name=@zone_name,reveiceTime=@reveiceTime,pick_up_tab=@PickUpTab where carton_no=@carton_no ");
                            DynamicParameters updateStringparameters = new DynamicParameters();
                            updateStringparameters.Add("@carton_no", cartonNo);
                            updateStringparameters.Add("@group_no", groupNo);
                            updateStringparameters.Add("@qty", sysStocks[0].Qty);
                            updateStringparameters.Add("@locate_id", locateId);
                            updateStringparameters.Add("@locate_name", locateName);
                            updateStringparameters.Add("@warehouse_id", warehouseId);
                            updateStringparameters.Add("@warehouse_name", warehouseName);
                            updateStringparameters.Add("@zone_id", zoneId);
                            updateStringparameters.Add("@zone_name", zoneName);
                            updateStringparameters.Add("@reveiceTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            updateStringparameters.Add("@update_userid", loginId);
                            updateStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            updateStringparameters.Add("@PickUpTab", "1");//捡料标记

                            sqlStrings.Add(updateString.ToString());
                            parameterList.Add(updateStringparameters);

                            //新增 sys_stock_trans 事务表
                            StringBuilder updateString4 = new StringBuilder(1024);
                            updateString4.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,@unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,@dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");

                            DynamicParameters updateStringparameters4 = new DynamicParameters();
                            updateStringparameters4.Add("@trans_code", (int)WmsEnumUtil.TransType.RC);
                            updateStringparameters4.Add("@carton_no", sysStocks[0].CartonNo);
                            updateStringparameters4.Add("@part_id", sysStocks[0].PartId);
                            updateStringparameters4.Add("@part_no", sysStocks[0].PartNo);
                            updateStringparameters4.Add("@part_spec", sysStocks[0].PartSpec);
                            updateStringparameters4.Add("@src_locate_id", 0);
                            updateStringparameters4.Add("@src_locate_name", null);
                            updateStringparameters4.Add("@dest_locate_id", locateId);
                            updateStringparameters4.Add("@dest_locate_name", locateName);
                            updateStringparameters4.Add("@old_qty", sysStocks[0].Qty);
                            updateStringparameters4.Add("@new_qty", sysStocks[0].Qty);
                            updateStringparameters4.Add("@trans_qty", sysStocks[0].Qty);
                            updateStringparameters4.Add("@old_status", 20);
                            updateStringparameters4.Add("@new_status", 25);
                            updateStringparameters4.Add("@old_qms_status", "N");
                            updateStringparameters4.Add("@new_qms_status", "N");
                            updateStringparameters4.Add("@unit", sysStocks[0].Unit);
                            updateStringparameters4.Add("@factory_id", sysStocks[0].FactoryId);
                            updateStringparameters4.Add("@factory_code", sysStocks[0].FactoryCode);
                            updateStringparameters4.Add("@src_erp_warehouse", sysStocks[0].ErpWarehouse);
                            updateStringparameters4.Add("@dest_erp_warehouse", sysStocks[0].ErpWarehouse);
                            updateStringparameters4.Add("@src_warehouse_id", 0);
                            updateStringparameters4.Add("@src_warehouse_name", "");
                            updateStringparameters4.Add("@dest_warehouse_id", warehouseId);
                            updateStringparameters4.Add("@dest_warehouse_name", warehouseName);
                            updateStringparameters4.Add("@src_zone_id", 0);
                            updateStringparameters4.Add("@src_zone_name", "");
                            updateStringparameters4.Add("@dest_zone_id", zoneId);
                            updateStringparameters4.Add("@dest_zone_name", zoneName);
                            updateStringparameters4.Add("@enabled", sysStocks[0].Enabled);
                            updateStringparameters4.Add("@update_userid", loginId);
                            updateStringparameters4.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            updateStringparameters4.Add("@create_userid", loginId);
                            updateStringparameters4.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            updateStringparameters4.Add("@guid", Guid.NewGuid());

                            sqlStrings.Add(updateString4.ToString());
                            parameterList.Add(updateStringparameters4);


                            //委外收货，新增 wms_subcontract_data
                            StringBuilder sqlSubcontract = new StringBuilder(1024);
                            sqlSubcontract.Append("select * from [dbo].[wms_purchase] where order_no=@orderNo ");
                            DynamicParameters parametersSubcontract = new DynamicParameters();
                            parametersSubcontract.Add("@orderNo", orderNo);
                            List<WmsPurchase> dtSubcontract = dbConn.Query<WmsPurchase>(sqlSubcontract.ToString(), parametersSubcontract).ToList();
                            if (dtSubcontract.Count > 0)
                            {
                                if (dtSubcontract[0].Pstyp == 3)
                                {
                                    StringBuilder updateString5 = new StringBuilder(1024);
                                    updateString5.Append(@" INSERT INTO[dbo].[wms_subcontract_data]
                                                    ([trans_code]
                                                     ,[part_id]
                                                     ,[part_no]
                                                     ,[part_spec]
                                                     ,[carton_no]
                                                     ,[qty]
                                                     ,[deal_qty]
                                                     ,[unit]
                                                     ,[deal_status]
                                                     ,[vendor_id]
                                                     ,[vendor_code]
                                                     ,[ref_order_no]
                                                     ,[factory_id]
                                                     ,[factory_code]
                                                     ,[enabled]
                                                     ,[create_userid]
                                                     ,[create_time]
                                                     ,[update_userid]
                                                     ,[update_time]
                                                     ,[guid]) 
                                                  VALUES ( @trans_code	 ,@part_id	 ,@part_no	 ,@part_spec	 ,@carton_no	 ,@qty	 ,@deal_qty	 ,@unit	 ,@deal_status	 ,@vendor_id	 ,@vendor_code	 ,@ref_order_no	 ,@factory_id	 ,@factory_code	 ,@enabled	 ,@create_userid
	                                         ,@create_time	 ,@update_userid	 ,@update_time	 ,@guid )");

                                    DynamicParameters updateStringparameters5 = new DynamicParameters();
                                    updateStringparameters5.Add("@trans_code", (int)WmsEnumUtil.PurchaseOrderType.SUB);
                                    updateStringparameters5.Add("@part_id", sysStocks[0].PartId);
                                    updateStringparameters5.Add("@part_no", sysStocks[0].PartNo);
                                    updateStringparameters5.Add("@part_spec", sysStocks[0].PartSpec);
                                    updateStringparameters5.Add("@carton_no", sysStocks[0].CartonNo);
                                    updateStringparameters5.Add("@qty", sysStocks[0].Qty);
                                    updateStringparameters5.Add("@deal_qty", 0);
                                    updateStringparameters5.Add("@unit", sysStocks[0].Unit);
                                    updateStringparameters5.Add("@deal_status", 10);
                                    updateStringparameters5.Add("@vendor_id", sysStocks[0].VendorId);
                                    updateStringparameters5.Add("@vendor_code", sysStocks[0].VendorCode);
                                    updateStringparameters5.Add("@ref_order_no", sysStocks[0].RefOrderNo);
                                    updateStringparameters5.Add("@factory_id", sysStocks[0].FactoryId);
                                    updateStringparameters5.Add("@factory_code", sysStocks[0].FactoryCode);
                                    updateStringparameters5.Add("@enabled", sysStocks[0].Enabled);
                                    updateStringparameters5.Add("@update_userid", loginId);
                                    updateStringparameters5.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                    updateStringparameters5.Add("@create_userid", loginId);
                                    updateStringparameters5.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                    updateStringparameters5.Add("@guid", Guid.NewGuid());

                                    sqlStrings.Add(updateString5.ToString());
                                    parameterList.Add(updateStringparameters5);
                                }
                            }


                            //执行事务
                            IDbTransaction transaction = dbConn.BeginTransaction();

                            bool successCount = true;
                            for (int i = 0; i < sqlStrings.Count; i++)
                            {
                                if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
                                {
                                    successCount = false;
                                }
                            }

                            if (successCount)
                            {
                                transaction.Commit();
                                result = "OK" + sysStocks[0].RefOrderNo;

                                #region 修改收货明细表

                                //判断订单是否收货完成
                                //                                StringBuilder Ischeckstock = new StringBuilder(1024);
                                //                                Ischeckstock.Append(@"select * from sys_stock where ref_order_no in (select ref_order_no from sys_stock where carton_no=@carton_no) 
                                //and part_id in (select part_id from sys_stock where carton_no = @carton_no) and status = '20'");
                                //                                DynamicParameters Ischeckparameters = new DynamicParameters();
                                //                                Ischeckparameters.Add("@carton_no", cartonNo);
                                //                                List<SysStock> CheckList = dbConn.Query<SysStock>(Ischeckstock.ToString(), Ischeckparameters).ToList();

                                //                                if (CheckList.Count == 0)
                                //                                {
                                //                                    //修改明细表
                                //                                    //更新收货明细表：实收数  更新状态：收货中
                                //                                    StringBuilder COMPLETEDString = new StringBuilder(1024);
                                //                                    COMPLETEDString.Append(@"update wms_purchase_detail set item_status=@item_status,update_userid=@update_userid,update_time=@update_time where order_no in (select ref_order_no from sys_stock where carton_no=@carton_no)  and part_id in (select part_id from sys_stock where carton_no =@carton_no)");
                                //                                    DynamicParameters COMPLETEDStringparameters = new DynamicParameters();
                                //                                    COMPLETEDStringparameters.Add("@carton_no", cartonNo);
                                //                                    COMPLETEDStringparameters.Add("@item_status", (int)WmsEnumUtil.PurchaseOrderDetailStatus.COMPLETED);
                                //                                    COMPLETEDStringparameters.Add("@update_userid", loginId);
                                //                                    COMPLETEDStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                //                                    dbConn.Execute(COMPLETEDString.ToString(), COMPLETEDStringparameters);
                                //                                }

                                #endregion

                                #region 修改收货主表
                                ////判断订单是否收货完成
                                //StringBuilder Ischeckpurchase = new StringBuilder(1024);
                                //Ischeckpurchase.Append(@"select * from wms_purchase_detail (nolock) where order_no in (select ref_order_no from sys_stock (nolock) where carton_no=@carton_no ) ");
                                //DynamicParameters Ischeckpurchaseparameters = new DynamicParameters();
                                //Ischeckpurchaseparameters.Add("@carton_no", cartonNo);
                                //Ischeckpurchaseparameters.Add("@item_status", (int)WmsEnumUtil.PurchaseOrderDetailStatus.COMPLETED);
                                //List<WmsPurchaseDetail> CheckPurchaseList = dbConn.Query<WmsPurchaseDetail>(Ischeckpurchase.ToString(), Ischeckpurchaseparameters).ToList();
                                //var x = CheckPurchaseList.Sum(a => a.ItemStatus);

                                //if (CheckPurchaseList.Count * 40 == x)
                                //{
                                //    //修改明细表
                                //    //更新收货表
                                //    StringBuilder COMPLETEDString = new StringBuilder(1024);
                                //    COMPLETEDString.Append(@" update wms_purchase set order_status=@order_status,update_userid=@update_userid,update_time=@update_time where order_no in (select ref_order_no from sys_stock (nolock) where carton_no=@carton_no )");
                                //    DynamicParameters COMPLETEDStringparameters = new DynamicParameters();
                                //    COMPLETEDStringparameters.Add("@carton_no", cartonNo);
                                //    COMPLETEDStringparameters.Add("@order_status", (int)WmsEnumUtil.PurchaseOrderStatus.COMPLETED);
                                //    COMPLETEDStringparameters.Add("@update_userid", loginId);
                                //    COMPLETEDStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                //    dbConn.Execute(COMPLETEDString.ToString(), COMPLETEDStringparameters);
                                //}
                                #endregion

                            }
                            else
                            {
                                transaction.Rollback();
                                result = "操作失败，请重新尝试！";
                            }

                        }
                        else
                        {
                            result = " [" + cartonNo + "] : 包装条码已收货!";
                        }
                    }
                    else
                    {
                        result = " [" + cartonNo + "] : 不在订单列表中!";
                    }
                }
                else
                {
                    result = " [" + cartonNo + "] : 包装条码无效!";
                }

                return result;
            }
        }

		public int DGcut(int a, int b)
        {
            int c = a - b;
            if (c > b)
            {
                return DGcut(c, b);
            }
            else
                return c;
        }

        /// <summary>
        /// 收货拒收，更改数据状态
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <returns></returns>
        public string UpdateCartonStatusInRejection(string cartonNo, string info, string loginId, string supportingParts)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                StringBuilder sql = new StringBuilder(1024);
                sql.Append("select * from sys_stock (nolock) where ref_order_no in ( select ref_order_no from sys_stock (nolock) where carton_no=@carton_no) ");
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@carton_no", cartonNo);

                List<SysStock> dt = dbConn.Query<SysStock>(sql.ToString(), parameters).ToList();
                string result = string.Empty;
                if (dt.Count > 0)
                {
                    List<SysStock> sysStocks = dt.Where(a => a.CartonNo == cartonNo && a.Enabled == "Y").ToList();
                    if (sysStocks.Count > 0)
                    {
                        if (sysStocks[0].Status == (int)WmsEnumUtil.StockStatus.WAITING_RECEIVE)
                        {
                            List<string> sqlStrings = new List<string>();
                            List<DynamicParameters> parameterList = new List<DynamicParameters>();

                            //更新收货明细表：实收数  更新状态：收货中
                            StringBuilder updateString = new StringBuilder(1024);
                            updateString.Append("update sys_stock set status='20',remark= remark + @info,reveiceTime=@reveiceTime where carton_no=@carton_no ");
                            DynamicParameters updateStringparameters = new DynamicParameters();
                            updateStringparameters.Add("@carton_no", cartonNo);
                            updateStringparameters.Add("@info", info);
                            updateStringparameters.Add("@reveiceTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            sqlStrings.Add(updateString.ToString());
                            parameterList.Add(updateStringparameters);


                            //还原收货主表状态：收货中
                            StringBuilder updateString2 = new StringBuilder(1024);
                            updateString2.Append("update wms_purchase set order_status='30',update_userid=@update_userid,update_time=@update_time where order_no=@order_no  ");
                            DynamicParameters updateStringparameters2 = new DynamicParameters();
                            updateStringparameters2.Add("@order_no", dt[0].RefOrderNo);
                            updateStringparameters2.Add("@update_userid", loginId);
                            updateStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            sqlStrings.Add(updateString2.ToString());
                            parameterList.Add(updateStringparameters2);


                            StringBuilder GetPurchaseDetail = new StringBuilder(1024);
                            GetPurchaseDetail.Append(@" select part_id,sum(qty) qty ,count(1) rec_box_qty from sys_stock (nolock) where ref_order_no=@order_no and part_id=@part_id and status > 20 group by part_id");
                            DynamicParameters GetPurchaseDetailparameters = new DynamicParameters();
                            GetPurchaseDetailparameters.Add("@order_no", dt[0].RefOrderNo);
                            GetPurchaseDetailparameters.Add("@part_id", dt[0].PartId);
                            List<WmsPurchaseDetail> PurchaseDetail = dbConn.Query<WmsPurchaseDetail>(sql.ToString(), parameters).ToList();

                            //还原收货明细表：实收数  更新状态：收货中
                            StringBuilder updateString3 = new StringBuilder(1024);
                            updateString3.Append("update wms_purchase_detail set item_status='30',rec_qty = rec_qty - @rec_qty,rec_box_qty= @rec_box_qty  ,update_userid=@update_userid,update_time=@update_time where order_no=@order_no and part_id=@part_id");
                            DynamicParameters updateStringparameters3 = new DynamicParameters();
                            updateStringparameters3.Add("@order_no", dt[0].RefOrderNo);
                            updateStringparameters3.Add("@rec_qty", PurchaseDetail.Count == 0 ? "0" : PurchaseDetail[0].Qty);
                            updateStringparameters3.Add("@rec_box_qty", PurchaseDetail.Count == 0 ? "0" : PurchaseDetail[0].RecBoxQty);
                            updateStringparameters3.Add("@part_id", dt[0].PartId);
                            updateStringparameters3.Add("@update_userid", loginId);
                            updateStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                            sqlStrings.Add(updateString3.ToString());
                            parameterList.Add(updateStringparameters3);


                            //新增 sys_stock_trans 事务表
                            StringBuilder updateString4 = new StringBuilder(1024);
                            updateString4.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,@unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,@dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");

                            DynamicParameters updateStringparameters4 = new DynamicParameters();
                            updateStringparameters4.Add("@trans_code", 150);
                            updateStringparameters4.Add("@carton_no", sysStocks[0].CartonNo);
                            updateStringparameters4.Add("@part_id", sysStocks[0].PartId);
                            updateStringparameters4.Add("@part_no", sysStocks[0].PartNo);
                            updateStringparameters4.Add("@part_spec", sysStocks[0].PartSpec);
                            updateStringparameters4.Add("@src_locate_id", 0);
                            updateStringparameters4.Add("@src_locate_name", null);
                            updateStringparameters4.Add("@dest_locate_id", 0);
                            updateStringparameters4.Add("@dest_locate_name", null);
                            updateStringparameters4.Add("@old_qty", sysStocks[0].Qty);
                            updateStringparameters4.Add("@new_qty", sysStocks[0].Qty);
                            updateStringparameters4.Add("@trans_qty", sysStocks[0].Qty);
                            updateStringparameters4.Add("@old_status", 20);
                            updateStringparameters4.Add("@new_status", 150);
                            updateStringparameters4.Add("@old_qms_status", "N");
                            updateStringparameters4.Add("@new_qms_status", "N");
                            updateStringparameters4.Add("@unit", sysStocks[0].Unit);
                            updateStringparameters4.Add("@factory_id", sysStocks[0].FactoryId);
                            updateStringparameters4.Add("@factory_code", sysStocks[0].FactoryCode);
                            updateStringparameters4.Add("@src_erp_warehouse", sysStocks[0].ErpWarehouse);
                            updateStringparameters4.Add("@dest_erp_warehouse", sysStocks[0].ErpWarehouse);
                            updateStringparameters4.Add("@src_warehouse_id", sysStocks[0].WarehouseId);
                            updateStringparameters4.Add("@src_warehouse_name", sysStocks[0].WarehouseName);
                            updateStringparameters4.Add("@dest_warehouse_id", sysStocks[0].WarehouseId);
                            updateStringparameters4.Add("@dest_warehouse_name", sysStocks[0].WarehouseName);
                            updateStringparameters4.Add("@src_zone_id", sysStocks[0].ZoneId);
                            updateStringparameters4.Add("@src_zone_name", sysStocks[0].ZoneName);
                            updateStringparameters4.Add("@dest_zone_id", sysStocks[0].ZoneId);
                            updateStringparameters4.Add("@dest_zone_name", sysStocks[0].ZoneName);
                            updateStringparameters4.Add("@enabled", sysStocks[0].Enabled);
                            updateStringparameters4.Add("@update_userid", loginId);
                            updateStringparameters4.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            updateStringparameters4.Add("@create_userid", loginId);
                            updateStringparameters4.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            updateStringparameters4.Add("@guid", Guid.NewGuid());

                            sqlStrings.Add(updateString4.ToString());
                            parameterList.Add(updateStringparameters4);

                            //执行事务
                            IDbTransaction transaction = dbConn.BeginTransaction();

                            bool successCount = true;
                            for (int i = 0; i < sqlStrings.Count; i++)
                            {
                                if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
                                {
                                    successCount = false;
                                }
                            }
                            if (successCount)
                            {
                                transaction.Commit();
                                result = "OK";
                            }
                            else
                            {
                                transaction.Rollback();
                                result = "操作失败，请重新尝试！";
                            }
                        }
                        else
                        {
                            result = " [" + cartonNo + "] : 包装条码不处于待收货状态!";
                        }
                    }
                    else
                    {
                        result = " [" + cartonNo + "] : 包装条码被冻结!";
                    }
                }
                else
                {
                    result = " [" + cartonNo + "] : 包装条码无效!";
                }
                return result;
            }
        }

        /// <summary>
        /// 收货拒收，更改数据状态
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <returns></returns>
        public string UpdateCartonStatusInRejectionBycd(string cartonNo, string info, string loginId, string supportingParts, string cdNum)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                StringBuilder sql = new StringBuilder(1024);
                sql.Append("select * from sys_stock (nolock) where ref_order_no in ( select ref_order_no from sys_stock (nolock) where carton_no=@carton_no) ");
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@carton_no", cartonNo);

                List<SysStock> dt = dbConn.Query<SysStock>(sql.ToString(), parameters).ToList();
                string result = string.Empty;
                if (dt.Count > 0)
                {
                    List<SysStock> sysStocks = dt.Where(a => a.CartonNo == cartonNo && a.Enabled == "Y").ToList();
                    if (sysStocks.Count > 0)
                    {
                        if (sysStocks[0].Status == (int)WmsEnumUtil.StockStatus.WAITING_RECEIVE)
                        {
                            List<string> sqlStrings = new List<string>();
                            List<DynamicParameters> parameterList = new List<DynamicParameters>();

                            //更新收货明细表：实收数  更新状态：收货中
                            StringBuilder updateString = new StringBuilder(1024);
                            updateString.Append("update sys_stock set status='150',remark= isnull(remark,'') + @info ,reveiceTime=@reveiceTime,count_qty = @cdNum where carton_no=@carton_no ");
                            DynamicParameters updateStringparameters = new DynamicParameters();
                            updateStringparameters.Add("@carton_no", cartonNo);
                            updateStringparameters.Add("@info", info);
                            updateStringparameters.Add("@cdNum", cdNum);
                            updateStringparameters.Add("@reveiceTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            sqlStrings.Add(updateString.ToString());
                            parameterList.Add(updateStringparameters);

                            //新增 sys_stock_trans 事务表
                            StringBuilder updateString4 = new StringBuilder(1024);
                            updateString4.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,@unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,@dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");


                            DynamicParameters updateStringparameters4 = new DynamicParameters();
                            updateStringparameters4.Add("@trans_code", 150);
                            updateStringparameters4.Add("@carton_no", sysStocks[0].CartonNo);
                            updateStringparameters4.Add("@part_id", sysStocks[0].PartId);
                            updateStringparameters4.Add("@part_no", sysStocks[0].PartNo);
                            updateStringparameters4.Add("@part_spec", sysStocks[0].PartSpec);
                            updateStringparameters4.Add("@src_locate_id", 0);
                            updateStringparameters4.Add("@src_locate_name", null);
                            updateStringparameters4.Add("@dest_locate_id", 0);
                            updateStringparameters4.Add("@dest_locate_name", null);
                            updateStringparameters4.Add("@old_qty", sysStocks[0].Qty);
                            updateStringparameters4.Add("@new_qty", cdNum);
                            updateStringparameters4.Add("@trans_qty", sysStocks[0].Qty);
                            updateStringparameters4.Add("@old_status", 20);
                            updateStringparameters4.Add("@new_status", 150);
                            updateStringparameters4.Add("@old_qms_status", "N");
                            updateStringparameters4.Add("@new_qms_status", "N");
                            updateStringparameters4.Add("@unit", sysStocks[0].Unit);
                            updateStringparameters4.Add("@factory_id", sysStocks[0].FactoryId);
                            updateStringparameters4.Add("@factory_code", sysStocks[0].FactoryCode);
                            updateStringparameters4.Add("@src_erp_warehouse", sysStocks[0].ErpWarehouse);
                            updateStringparameters4.Add("@dest_erp_warehouse", sysStocks[0].ErpWarehouse);
                            updateStringparameters4.Add("@src_warehouse_id", sysStocks[0].WarehouseId);
                            updateStringparameters4.Add("@src_warehouse_name", sysStocks[0].WarehouseName);
                            updateStringparameters4.Add("@dest_warehouse_id", sysStocks[0].WarehouseId);
                            updateStringparameters4.Add("@dest_warehouse_name", sysStocks[0].WarehouseName);
                            updateStringparameters4.Add("@src_zone_id", sysStocks[0].ZoneId);
                            updateStringparameters4.Add("@src_zone_name", sysStocks[0].ZoneName);
                            updateStringparameters4.Add("@dest_zone_id", sysStocks[0].ZoneId);
                            updateStringparameters4.Add("@dest_zone_name", sysStocks[0].ZoneName);
                            updateStringparameters4.Add("@enabled", sysStocks[0].Enabled);
                            updateStringparameters4.Add("@update_userid", loginId);
                            updateStringparameters4.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            updateStringparameters4.Add("@create_userid", loginId);
                            updateStringparameters4.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            updateStringparameters4.Add("@guid", Guid.NewGuid());

                            sqlStrings.Add(updateString4.ToString());
                            parameterList.Add(updateStringparameters4);

                            //执行事务
                            IDbTransaction transaction = dbConn.BeginTransaction();

                            bool successCount = true;
                            for (int i = 0; i < sqlStrings.Count; i++)
                            {
                                if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
                                {
                                    successCount = false;
                                }
                            }
                            if (successCount)
                            {
                                transaction.Commit();
                                result = "OK";
                            }
                            else
                            {
                                transaction.Rollback();
                                result = "操作失败，请重新尝试！";
                            }
                        }
                        else
                        {
                            result = " [" + cartonNo + "] : 包装条码不处于待收货状态!";
                        }
                    }
                    else
                    {
                        result = " [" + cartonNo + "] : 包装条码被冻结!";
                    }
                }
                else
                {
                    result = " [" + cartonNo + "] : 包装条码无效!";
                }
                return result;
            }
        }

        /// <summary>
        /// 拒收 还原订单
        /// </summary>
        /// <param name="loginId"></param>
        /// <param name="cartonNo"></param>
        public void ChangePurchase(string loginId, string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                StringBuilder sql = new StringBuilder(1024);
                sql.Append("select * from sys_stock (nolock) where ref_order_no in ( select ref_order_no from sys_stock (nolock) where carton_no=@carton_no) ");
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@carton_no", cartonNo);

                List<SysStock> dt = dbConn.Query<SysStock>(sql.ToString(), parameters).ToList();

                List<string> sqlStrings = new List<string>();
                List<DynamicParameters> parameterList = new List<DynamicParameters>();


                //还原收货主表状态：收货中
                StringBuilder updateString2 = new StringBuilder(1024);
                updateString2.Append("update wms_purchase set order_status='30',update_userid=@update_userid,update_time=@update_time where order_no=@order_no  ");
                DynamicParameters updateStringparameters2 = new DynamicParameters();
                updateStringparameters2.Add("@order_no", dt[0].RefOrderNo);
                updateStringparameters2.Add("@update_userid", loginId);
                updateStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                sqlStrings.Add(updateString2.ToString());
                parameterList.Add(updateStringparameters2);


                //还原收货明细表：实收数  更新状态：收货中
                StringBuilder updateString3 = new StringBuilder(1024);
                updateString3.Append("update wms_purchase_detail set item_status='30',rec_qty = rec_qty - @rec_qty,rec_box_qty= rec_box_qty - 1  ,update_userid=@update_userid,update_time=@update_time where order_no=@order_no and part_id=@part_id");
                DynamicParameters updateStringparameters3 = new DynamicParameters();
                updateStringparameters3.Add("@order_no", dt[0].RefOrderNo);
                updateStringparameters3.Add("@rec_qty", dt[0].Qty);
                updateStringparameters3.Add("@part_id", dt[0].PartId);
                updateStringparameters3.Add("@update_userid", loginId);
                updateStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                sqlStrings.Add(updateString3.ToString());
                parameterList.Add(updateStringparameters3);

                //执行事务
                IDbTransaction inserttransaction = dbConn.BeginTransaction();

                bool successCount = true;
                for (int i = 0; i < sqlStrings.Count; i++)
                {
                    if (dbConn.Execute(sqlStrings[i], parameterList[i], inserttransaction) < 1)
                    {
                        successCount = false;
                    }
                }

                if (successCount)
                {
                    inserttransaction.Commit();
                }
                else
                {
                    inserttransaction.Rollback();
                }
            }
        }
        /// <summary>
        /// 通过箱条码获取收货订单的明细信息  , 支给件没有信息就新增信息
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <param name="receving"></param>
        /// <returns></returns>
        public SetObjectDetail GetCartonSummaryInfo(string cartonNo, string receving, string supportingParts, string loginId)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                SetObjectDetail setDetail = new SetObjectDetail();
                string zgj_order = string.Empty;

                if (supportingParts == "Y")
                {
                    #region 支给件逻辑

                    //二维码当箱条码使用
                    //零件号#包装数#采购订单号#行号#物流订单号#零件简号#追溯重要度等级#供应商代码#批次号#同批次数量#供应商出货地-16位随机码
                    //cartonNo = "8040007ARD0000#300#AM22Y23597#20#AM22Y23597#ZG022#01##SN301#@#300#8096e87d41ad41afbf24b2aef6bbce4b#1";
                    string[] cartonNoList = cartonNo.Split('#');
                    string cust_part_no = string.Empty;
                    string zgj_qty = string.Empty;

                    string zgj_itemidex = string.Empty;
                    string zgj_WLorder = string.Empty;
                    string zgj_partspec = string.Empty;
                    string zgj_level = string.Empty;
                    string zgj_vendor = string.Empty;
                    string zgj_lotno = string.Empty;
                    string zgj_lotno_num = string.Empty;
                    string zgj_vendor_address = string.Empty;
                    if (cartonNoList.Length == 13)
                    {
                        cust_part_no = cartonNoList[0].ToString();//客户零件号
                        zgj_qty = cartonNoList[1].ToString();//包装数
                        zgj_order = cartonNoList[2].ToString();//采购订单号
                        zgj_itemidex = cartonNoList[3].ToString();//行号   1
                        zgj_WLorder = cartonNoList[4].ToString();//物流订单号  1
                        zgj_partspec = cartonNoList[5].ToString();//零件简号  1
                        zgj_level = cartonNoList[6].ToString();//追溯重要度等级  1
                        zgj_vendor = cartonNoList[8].ToString();//供应商代码
                        zgj_lotno = cartonNoList[8].ToString();//确认一下 批次号
                        zgj_lotno_num = cartonNoList[9].ToString();//同批次数量   1 
                        zgj_vendor_address = cartonNoList[10].ToString();//供应商出货地    1

                    }
                    else if (cartonNoList.Length == 12)
                    {
                        cust_part_no = cartonNoList[0].ToString();//客户零件号
                        zgj_qty = cartonNoList[10].ToString();//包装数
                        zgj_order = cartonNoList[2].ToString();//采购订单号
                        zgj_itemidex = cartonNoList[3].ToString();//行号   1
                        zgj_WLorder = cartonNoList[4].ToString();//物流订单号  1
                        zgj_partspec = cartonNoList[5].ToString();//零件简号  1
                        zgj_level = cartonNoList[6].ToString();//追溯重要度等级  1
                        zgj_vendor = cartonNoList[8].ToString();//供应商代码
                        zgj_lotno = cartonNoList[8].ToString();//批次号
                        zgj_lotno_num = cartonNoList[9].ToString();//同批次数量   1 
                        zgj_vendor_address = cartonNoList[10].ToString();//供应商出货地    1

                    }
                    else
                    {
                        setDetail.type = "NO";
                        setDetail.message = "二维码解析失败，请确认！";
                        setDetail.wmsObjectDetail = null;
                        return setDetail;
                    }

                    if (receving != "" && receving != zgj_order)
                    {
                        setDetail.type = "NO";
                        setDetail.message = "该条码不在此订单内！";
                        setDetail.wmsObjectDetail = null;
                        return setDetail;
                    }

                    //验证扫描的二维码里的零件号，在零件表中是否存在
                    StringBuilder getCustPartSQL = new StringBuilder(1024);
                    getCustPartSQL.Append("  select part_id,part_no,part_spec,factory_id,factory_code from wms_customer_to_stock where customer_part = @cust_part_no ");
                    DynamicParameters getCustPartparameters = new DynamicParameters();
                    getCustPartparameters.Add("@cust_part_no", cust_part_no);
                    List<SysStock> SysPart = dbConn.Query<SysStock>(getCustPartSQL.ToString(), getCustPartparameters).ToList();

                    string partId = string.Empty;//己主零件ID
                    string part_no = string.Empty;//己方零件号
                    if (SysPart.Count > 0)
                    {
                        partId = SysPart[0].PartId.ToString();
                        part_no = SysPart[0].PartNo;
                        zgj_partspec = SysPart[0].PartSpec;
                    }
                    else
                    {
                        setDetail.type = "NO";
                        setDetail.message = "[" + cust_part_no + "]:零件号不存在，为无效二维码，请确认！";
                        setDetail.wmsObjectDetail = null;
                        return setDetail;
                    }

                    //判断箱条码是否已存在
                    StringBuilder ifcartonNoSql = new StringBuilder(1024);
                    ifcartonNoSql.Append("select * from sys_stock (nolock) where carton_no = @carton_no ");
                    DynamicParameters ifcartonNoparameters = new DynamicParameters();
                    ifcartonNoparameters.Add("@carton_no", cartonNo);
                    List<SysStock> getcartonNo = dbConn.Query<SysStock>(ifcartonNoSql.ToString(), ifcartonNoparameters).ToList();
                    if (getcartonNo.Count > 0)
                    {
                        setDetail.type = "NO";
                        setDetail.message = "[" + cust_part_no + "]:已扫描，请确认！";
                        setDetail.wmsObjectDetail = null;
                        return setDetail;
                    }

                    //SQL 执行集合
                    List<string> insertStrings = new List<string>();
                    List<DynamicParameters> insertparameterList = new List<DynamicParameters>();

                    //获取供应商信息
                    #region 获取供应商信息


                    StringBuilder getCustPartSQL2 = new StringBuilder(1024);
                    getCustPartSQL2.Append("   select * from sys_vendor (nolock) where vendor_code=@vendor_code ");
                    DynamicParameters getCustPartparameters2 = new DynamicParameters();
                    getCustPartparameters2.Add("@vendor_code", zgj_vendor);
                    List<SysVendor> vendors = dbConn.Query<SysVendor>(getCustPartSQL2.ToString(), getCustPartparameters2).ToList();

                    string vendor_id = "";
                    string vendor_code = "";
                    string vendor_name = "";
                    if (vendors != null && vendors.Count > 0)
                    {
                        vendor_id = vendors[0].VendorId.ToString();
                        vendor_code = vendors[0].VendorCode.ToString();
                        vendor_name = vendors[0].VendorName.ToString();
                    }
                    else
                    {
                        vendor_code = zgj_vendor;
                        vendor_name = zgj_vendor;
                        //setDetail.type = "NO";
                        //setDetail.message = "[" + zgj_vendor + "]:供应商代码不存在，请确认！";
                        //setDetail.wmsObjectDetail = null;
                        //return setDetail;
                    }
                    #endregion
                    string dock = "";
                    string factory_id = SysPart[0].FactoryId.ToString();
                    string factory_code = SysPart[0].FactoryCode.ToString();
                    string partNum = zgj_qty;//零件数量
                    string part_snpNum = zgj_qty;
                    string unit = "";
                    string part_id = partId;
                    string part_spec = zgj_partspec;
                    string locate_id = "";
                    string locate_name = "";

                    StringBuilder getCustPartSQL3 = new StringBuilder(1024);
                    getCustPartSQL3.Append("select * from sys_locate (nolock) where locate_type =@locate_type  ");
                    DynamicParameters getCustPartparameters3 = new DynamicParameters();
                    getCustPartparameters3.Add("@locate_type", (int)WmsEnumUtil.LocateType.COLLECT_LOCATE);
                    List<SysLocate> syslocates = dbConn.Query<SysLocate>(getCustPartSQL3.ToString(), getCustPartparameters3).ToList();

                    if (syslocates != null && syslocates.Count > 0)
                    {
                        locate_id = syslocates[0].LocateId.ToString();
                        locate_name = syslocates[0].LocateName.ToString();
                    }
                    else
                    {
                        setDetail.type = "NO";
                        setDetail.message = "收货库位不存在，请确认！";
                        setDetail.wmsObjectDetail = null;
                        return setDetail;
                    }

                    
                    if (receving == "")
                    {
                        StringBuilder purchaseSql = new StringBuilder(1024);
                        purchaseSql.Append("select * from wms_purchase (nolock) where order_no = @order_no");
                        DynamicParameters purchaseparameters = new DynamicParameters();
                        purchaseparameters.Add("@order_no", zgj_order);
                        List<WmsPurchase> getPurchase = dbConn.Query<WmsPurchase>(purchaseSql.ToString(), purchaseparameters).ToList();
                        if (getPurchase.Count > 0)
                        {
                            receving = getPurchase[0].OrderNo;
                        }
                    }


                    //验证扫描的零件号，增加 主表 从表 条码表
                    if (receving.Length > 0)//已存在支给件收货订单
                    {
                        StringBuilder getStockSql = new StringBuilder(1024);
                        getStockSql.Append("select * from sys_stock (nolock) where ref_order_no = @ref_order_no");
                        DynamicParameters getStockparameters = new DynamicParameters();
                        getStockparameters.Add("@ref_order_no", receving);
                        List<SysStock> getStock = dbConn.Query<SysStock>(getStockSql.ToString(), getStockparameters).ToList();

                        List<SysStock> sys_cartonNo = getStock.Where(a => a.CartonNo == cartonNo && a.Enabled == "Y").ToList();

                        if (sys_cartonNo.Count > 0)
                        {
                            setDetail.type = "NO";
                            setDetail.message = "此标签已扫描，请确认！";
                            setDetail.wmsObjectDetail = null;
                            return setDetail;
                        }
                        else //箱条码不存在，新增
                        {
                            #region 新增库存条码表

                            StringBuilder insertString3 = new StringBuilder(1024);
                            insertString3.Append(@" INSERT INTO [dbo].[sys_stock]
                                             ([vendor_id]
                                             ,[vendor_code]
                                             ,[carton_no]
                                             ,[part_id]
                                             ,[part_no]
                                             ,[part_spec]
                                             ,[lot_no]
                                             ,[fix_lot_no]
                                             ,[status]
                                             ,[qty]
                                             ,[snp_qty]
                                             ,[locate_id]
                                             ,[locate_name]
                                             ,[group_no]
                                             ,[erp_warehouse]
                                             ,[date_code]
                                             ,[qms_status]
                                             ,[ref_order_no]
                                             ,[unit]
                                             ,[dock]
                                             ,[warehouse_id]
                                             ,[warehouse_name]
                                             ,[zone_id]
                                             ,[zone_name]
                                             ,[printed]
                                             ,[print_time]
                                             ,[remark]
                                             ,[factory_id]
                                             ,[factory_code]
                                             ,[enabled]
                                             ,[create_userid]
                                             ,[create_time]
                                             ,[update_userid]
                                             ,[update_time]
                                             ,[guid])
                                              VALUES ( @vendor_id ,@vendor_code ,@carton_no ,@part_id ,@part_no ,@part_spec ,@lot_no ,@fix_lot_no ,@status ,@qty ,@snp_qty ,@locate_id ,@locate_name ,@group_no ,@erp_warehouse ,@date_code ,@qms_status ,@ref_order_no ,@unit ,@dock ,@warehouse_id ,@warehouse_name ,@zone_id ,@zone_name ,@printed ,@print_time ,@remark ,@factory_id ,@factory_code ,@enabled ,@create_userid ,@create_time ,@update_userid ,@update_time ,@guid )");

                            DynamicParameters insertStringparameters3 = new DynamicParameters();
                            insertStringparameters3.Add("@vendor_id ", vendor_id);
                            insertStringparameters3.Add("@vendor_code ", vendor_name);
                            insertStringparameters3.Add("@carton_no ", cartonNo);
                            insertStringparameters3.Add("@part_id ", part_id);
                            insertStringparameters3.Add("@part_no ", part_no);
                            insertStringparameters3.Add("@part_spec ", part_spec);
                            insertStringparameters3.Add("@lot_no ", "");
                            insertStringparameters3.Add("@fix_lot_no ", "");
                            insertStringparameters3.Add("@status ", 20);
                            insertStringparameters3.Add("@qty ", partNum);
                            insertStringparameters3.Add("@snp_qty ", part_snpNum);
                            insertStringparameters3.Add("@locate_id ", "");
                            insertStringparameters3.Add("@locate_name ", "");
                            insertStringparameters3.Add("@group_no ", "");
                            insertStringparameters3.Add("@erp_warehouse ", "");
                            insertStringparameters3.Add("@date_code ", "");
                            insertStringparameters3.Add("@qms_status ", "");
                            insertStringparameters3.Add("@ref_order_no ", receving);
                            insertStringparameters3.Add("@unit ", unit);
                            insertStringparameters3.Add("@dock ", dock);
                            insertStringparameters3.Add("@warehouse_id ", "");
                            insertStringparameters3.Add("@warehouse_name ", "");
                            insertStringparameters3.Add("@zone_id ", "");
                            insertStringparameters3.Add("@zone_name ", "");
                            insertStringparameters3.Add("@printed ", "");
                            insertStringparameters3.Add("@print_time ", "");
                            insertStringparameters3.Add("@remark ", "");
                            insertStringparameters3.Add("@factory_id ", factory_id);
                            insertStringparameters3.Add("@factory_code ", factory_code);
                            insertStringparameters3.Add("@enabled", "Y");
                            insertStringparameters3.Add("@update_userid", loginId);
                            insertStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            insertStringparameters3.Add("@create_userid", loginId);
                            insertStringparameters3.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            insertStringparameters3.Add("@guid", Guid.NewGuid());

                            insertStrings.Add(insertString3.ToString());
                            insertparameterList.Add(insertStringparameters3);
                            #endregion

                            //判断明细表中此箱条码的零件号是否存在

                            StringBuilder getPurchaseDetailSQL = new StringBuilder(1024);
                            getPurchaseDetailSQL.Append("SELECT * FROM wms_purchase_detail (nolock) WHERE order_no= @order_no ");
                            DynamicParameters wmsPurchaseDetailParameters = new DynamicParameters();
                            wmsPurchaseDetailParameters.Add("@order_no", receving);
                            List<WmsPurchaseDetail> ifPurchaseDetail = dbConn.Query<WmsPurchaseDetail>(getPurchaseDetailSQL.ToString(), wmsPurchaseDetailParameters).ToList();

                            List<WmsPurchaseDetail> ifPurchaseDetailByPart = ifPurchaseDetail.Where(a => a.PartNo == part_no && a.Enabled == "Y").ToList();

                            if (ifPurchaseDetailByPart.Count > 0)
                            {
                                #region 修改采购明细表
                                StringBuilder updateString2 = new StringBuilder(1024);

                                updateString2.Append(@" update wms_purchase_detail set qty= qty + @qty ,update_userid = @update_userid ,update_time =@update_time where  guid =@guid");

                                DynamicParameters updateStringparameters2 = new DynamicParameters();
                                updateStringparameters2.Add("@qty", partNum);
                                updateStringparameters2.Add("@update_userid", loginId);
                                updateStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                updateStringparameters2.Add("@guid", ifPurchaseDetailByPart[0].Guid);
                                insertStrings.Add(updateString2.ToString());
                                insertparameterList.Add(updateStringparameters2);
                                #endregion
                            }
                            else
                            {
                                #region 新增采购明细表
                                StringBuilder insertString2 = new StringBuilder(1024);
                                insertString2.Append(@"INSERT INTO [dbo].[wms_purchase_detail]
                                        ([order_no]
                                       ,[item_no]
                                       ,[part_id]
                                       ,[part_no]
                                       ,[part_spec]
                                       ,[qty]
                                       ,[rec_qty]
                                       ,[box_qty]
                                       ,[rec_box_qty]
                                       ,[snp_qty]
                                       ,[unit]
                                       ,[erp_warehouse]
                                       ,[item_status]
                                       ,[factory_id]
                                       ,[factory_code]
                                       ,[enabled]
                                       ,[create_userid]
                                       ,[create_time]
                                       ,[update_userid]
                                       ,[update_time]
                                       ,[guid])
                                 VALUES (@order_no ,@item_no ,@part_id ,@part_no ,@part_spec ,@qty ,@rec_qty ,@box_qty ,@rec_box_qty ,@snp_qty ,@unit ,@erp_warehouse 
                                    ,@item_status ,@factory_id ,@factory_code ,@enabled ,@create_userid ,@create_time ,@update_userid ,@update_time ,@guid ) ");

                                DynamicParameters insertStringparameters2 = new DynamicParameters();
                                insertStringparameters2.Add("@order_no", receving);
                                insertStringparameters2.Add("@item_no", getStock.Count + 1);
                                insertStringparameters2.Add("@part_id", part_id);
                                insertStringparameters2.Add("@part_no", part_no);
                                insertStringparameters2.Add("@part_spec", part_spec);
                                insertStringparameters2.Add("@qty", partNum);
                                insertStringparameters2.Add("@rec_qty", "0");
                                insertStringparameters2.Add("@box_qty", "0");
                                insertStringparameters2.Add("@rec_box_qty", "0");
                                insertStringparameters2.Add("@snp_qty", "0");
                                insertStringparameters2.Add("@unit", unit);
                                insertStringparameters2.Add("@erp_warehouse", "");
                                insertStringparameters2.Add("@item_status", 30);
                                insertStringparameters2.Add("@factory_id", factory_id);
                                insertStringparameters2.Add("@factory_code", factory_code);
                                insertStringparameters2.Add("@enabled", "Y");
                                insertStringparameters2.Add("@update_userid", loginId);
                                insertStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                insertStringparameters2.Add("@create_userid", loginId);
                                insertStringparameters2.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                insertStringparameters2.Add("@guid", Guid.NewGuid());
                                insertStrings.Add(insertString2.ToString());
                                insertparameterList.Add(insertStringparameters2);

                                #endregion
                            }
                        }
                    }
                    else //不存在支给件订单
                    {
                        //string order_no = GetOrderNo("SupportingPurchaseOrders", "ZGJ");
                        string order_no = zgj_order;
                        #region 新增采购订单表

                        StringBuilder insertString = new StringBuilder(1024);
                        insertString.Append(@"INSERT INTO [dbo].[wms_purchase]
                                         ([order_no]
                                         ,[order_type]
                                         ,[order_status]
                                         ,[vendor_id]
                                         ,[vendor_code]
                                         ,[se_date]
                                         ,[se_time]
                                         ,[dock]
                                         ,[ref_order_no]
                                         ,[factory_id]
                                         ,[factory_code]
                                         ,[enabled]
                                         ,[create_userid]
                                         ,[create_time]
                                         ,[update_userid]
                                         ,[update_time]
                                         ,[guid])
                                         VALUES (@order_no,@order_type,@order_status,@vendor_id,@vendor_code,@se_date,@se_time,@dock,@ref_order_no,@factory_id,
                                            @factory_code,@enabled,@create_userid,@create_time,@update_userid,@update_time,@guid)");

                        DynamicParameters insertStringparameters = new DynamicParameters();
                        insertStringparameters.Add("@order_no", order_no);
                        insertStringparameters.Add("@order_type", 40);
                        insertStringparameters.Add("@order_status", 30);
                        insertStringparameters.Add("@vendor_id", vendor_id);
                        insertStringparameters.Add("@vendor_code", vendor_code);
                        insertStringparameters.Add("@se_date", "");
                        insertStringparameters.Add("@se_time", "");
                        insertStringparameters.Add("@dock", dock);
                        insertStringparameters.Add("@ref_order_no", order_no);
                        insertStringparameters.Add("@factory_id", factory_id);
                        insertStringparameters.Add("@factory_code", factory_code);
                        insertStringparameters.Add("@enabled", "Y");
                        insertStringparameters.Add("@update_userid", loginId);
                        insertStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        insertStringparameters.Add("@create_userid", loginId);
                        insertStringparameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        insertStringparameters.Add("@guid", Guid.NewGuid());

                        insertStrings.Add(insertString.ToString());
                        insertparameterList.Add(insertStringparameters);

                        #endregion

                        #region 新增采购明细表
                        StringBuilder insertString2 = new StringBuilder(1024);
                        insertString2.Append(@"INSERT INTO [dbo].[wms_purchase_detail]
                                        ([order_no]
                                       ,[item_no]
                                       ,[part_id]
                                       ,[part_no]
                                       ,[part_spec]
                                       ,[qty]
                                       ,[rec_qty]
                                       ,[box_qty]
                                       ,[rec_box_qty]
                                       ,[snp_qty]
                                       ,[unit]
                                       ,[erp_warehouse]
                                       ,[item_status]
                                       ,[factory_id]
                                       ,[factory_code]
                                       ,[enabled]
                                       ,[create_userid]
                                       ,[create_time]
                                       ,[update_userid]
                                       ,[update_time]
                                       ,[guid])
                                 VALUES (@order_no ,@item_no ,@part_id ,@part_no ,@part_spec ,@qty, @rec_qty ,@box_qty ,@rec_box_qty ,@snp_qty ,@unit ,@erp_warehouse,@item_status ,@factory_id ,@factory_code ,@enabled ,@create_userid ,@create_time ,@update_userid ,@update_time ,@guid ) ");

                        DynamicParameters insertStringparameters2 = new DynamicParameters();
                        insertStringparameters2.Add("@order_no", order_no);
                        insertStringparameters2.Add("@item_no", 1);
                        insertStringparameters2.Add("@part_id", part_id);
                        insertStringparameters2.Add("@part_no", part_no);
                        insertStringparameters2.Add("@part_spec", part_spec);
                        insertStringparameters2.Add("@qty", partNum);
                        insertStringparameters2.Add("@rec_qty", "0");
                        insertStringparameters2.Add("@box_qty", "0");
                        insertStringparameters2.Add("@rec_box_qty", "0");
                        insertStringparameters2.Add("@snp_qty", "0");
                        insertStringparameters2.Add("@unit", unit);
                        insertStringparameters2.Add("@erp_warehouse", "");
                        insertStringparameters2.Add("@item_status", 30);
                        insertStringparameters2.Add("@factory_id", factory_id);
                        insertStringparameters2.Add("@factory_code", factory_code);
                        insertStringparameters2.Add("@enabled", "Y");
                        insertStringparameters2.Add("@update_userid", loginId);
                        insertStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        insertStringparameters2.Add("@create_userid", loginId);
                        insertStringparameters2.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        insertStringparameters2.Add("@guid", Guid.NewGuid());
                        insertStrings.Add(insertString2.ToString());
                        insertparameterList.Add(insertStringparameters2);

                        #endregion

                        #region 新增库存条码表
                        StringBuilder insertString3 = new StringBuilder(1024);
                        insertString3.Append(@" INSERT INTO [dbo].[sys_stock]
                                             ([vendor_id]
                                             ,[vendor_code]
                                             ,[carton_no]
                                             ,[part_id]
                                             ,[part_no]
                                             ,[part_spec]
                                             ,[lot_no]
                                             ,[fix_lot_no]
                                             ,[status]
                                             ,[qty]
                                             ,[snp_qty]
                                             ,[locate_id]
                                             ,[locate_name]
                                             ,[group_no]
                                             ,[erp_warehouse]
                                             ,[date_code]
                                             ,[qms_status]
                                             ,[ref_order_no]
                                             ,[unit]
                                             ,[dock]
                                             ,[warehouse_id]
                                             ,[warehouse_name]
                                             ,[zone_id]
                                             ,[zone_name]
                                             ,[printed]
                                             ,[print_time]
                                             ,[remark]
                                             ,[factory_id]
                                             ,[factory_code]
                                             ,[enabled]
                                             ,[create_userid]
                                             ,[create_time]
                                             ,[update_userid]
                                             ,[update_time]
                                             ,[guid])
                                              VALUES ( @vendor_id ,@vendor_code ,@carton_no ,@part_id ,@part_no ,@part_spec ,@lot_no ,@fix_lot_no ,@status ,@qty ,@snp_qty ,@locate_id ,@locate_name ,@group_no ,@erp_warehouse ,@date_code ,@qms_status ,@ref_order_no ,@unit ,@dock ,@warehouse_id ,@warehouse_name ,@zone_id ,@zone_name ,@printed ,@print_time ,@remark ,@factory_id ,@factory_code ,@enabled ,@create_userid ,@create_time ,@update_userid ,@update_time ,@guid )");

                        DynamicParameters insertStringparameters3 = new DynamicParameters();
                        insertStringparameters3.Add("@vendor_id ", vendor_id);
                        insertStringparameters3.Add("@vendor_code ", vendor_name);
                        insertStringparameters3.Add("@carton_no ", cartonNo);
                        insertStringparameters3.Add("@part_id ", part_id);
                        insertStringparameters3.Add("@part_no ", part_no);
                        insertStringparameters3.Add("@part_spec ", part_spec);
                        insertStringparameters3.Add("@lot_no ", zgj_lotno);
                        insertStringparameters3.Add("@fix_lot_no ", "");
                        insertStringparameters3.Add("@status ", 20);
                        insertStringparameters3.Add("@qty ", partNum);
                        insertStringparameters3.Add("@snp_qty ", part_snpNum);
                        insertStringparameters3.Add("@locate_id ", locate_id);
                        insertStringparameters3.Add("@locate_name ", locate_name);
                        insertStringparameters3.Add("@group_no ", "");
                        insertStringparameters3.Add("@erp_warehouse ", "");
                        insertStringparameters3.Add("@date_code ", "");
                        insertStringparameters3.Add("@qms_status ", "");
                        insertStringparameters3.Add("@ref_order_no ", order_no);
                        insertStringparameters3.Add("@unit ", unit);
                        insertStringparameters3.Add("@dock ", dock);
                        insertStringparameters3.Add("@warehouse_id ", "");
                        insertStringparameters3.Add("@warehouse_name ", "");
                        insertStringparameters3.Add("@zone_id ", "");
                        insertStringparameters3.Add("@zone_name ", "");
                        insertStringparameters3.Add("@printed ", "");
                        insertStringparameters3.Add("@print_time ", "");
                        insertStringparameters3.Add("@remark ", "");
                        insertStringparameters3.Add("@factory_id ", factory_id);
                        insertStringparameters3.Add("@factory_code ", factory_code);
                        insertStringparameters3.Add("@enabled", "Y");
                        insertStringparameters3.Add("@update_userid", loginId);
                        insertStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        insertStringparameters3.Add("@create_userid", loginId);
                        insertStringparameters3.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        insertStringparameters3.Add("@guid", Guid.NewGuid());

                        insertStrings.Add(insertString3.ToString());
                        insertparameterList.Add(insertStringparameters3);
                        #endregion

                        #region sys_stock_trans 事务表
                        StringBuilder insertString4 = new StringBuilder(1024);
                        insertString4.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,@unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,@dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");

                        DynamicParameters insertStringparameters4 = new DynamicParameters();
                        insertStringparameters4.Add("@trans_code", 30);
                        insertStringparameters4.Add("@carton_no", cartonNo);
                        insertStringparameters4.Add("@part_id", part_id);
                        insertStringparameters4.Add("@part_no", part_no);
                        insertStringparameters4.Add("@part_spec", part_spec);
                        insertStringparameters4.Add("@src_locate_id", 0);
                        insertStringparameters4.Add("@src_locate_name", "");
                        insertStringparameters4.Add("@dest_locate_id", locate_id);
                        insertStringparameters4.Add("@dest_locate_name", locate_name);
                        insertStringparameters4.Add("@old_qty", "0");
                        insertStringparameters4.Add("@new_qty", "0");
                        insertStringparameters4.Add("@trans_qty", "0");
                        insertStringparameters4.Add("@old_status", 0);
                        insertStringparameters4.Add("@new_status", 20);
                        insertStringparameters4.Add("@old_qms_status", "N");
                        insertStringparameters4.Add("@new_qms_status", "N");
                        insertStringparameters4.Add("@unit", unit);
                        insertStringparameters4.Add("@factory_id", factory_id);
                        insertStringparameters4.Add("@factory_code", factory_code);
                        insertStringparameters4.Add("@src_erp_warehouse", "");
                        insertStringparameters4.Add("@dest_erp_warehouse", "");
                        insertStringparameters4.Add("@src_warehouse_id", "");
                        insertStringparameters4.Add("@src_warehouse_name", "");
                        insertStringparameters4.Add("@dest_warehouse_id", "");
                        insertStringparameters4.Add("@dest_warehouse_name", "");
                        insertStringparameters4.Add("@src_zone_id", "");
                        insertStringparameters4.Add("@src_zone_name", "");
                        insertStringparameters4.Add("@dest_zone_id", "");
                        insertStringparameters4.Add("@dest_zone_name", "");
                        insertStringparameters4.Add("@enabled", "Y");
                        insertStringparameters4.Add("@update_userid", loginId);
                        insertStringparameters4.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        insertStringparameters4.Add("@create_userid", loginId);
                        insertStringparameters4.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        insertStringparameters4.Add("@guid", Guid.NewGuid());

                        insertStrings.Add(insertString4.ToString());
                        insertparameterList.Add(insertStringparameters4);
                        #endregion
                    }

                    //执行事务
                    IDbTransaction inserttransaction = dbConn.BeginTransaction();

                    bool successCount = true;
                    for (int i = 0; i < insertStrings.Count; i++)
                    {
                        if (dbConn.Execute(insertStrings[i], insertparameterList[i], inserttransaction) < 1)
                        {
                            successCount = false;
                        }
                    }

                    if (successCount)
                    {
                        inserttransaction.Commit();
                        //setDetail.type = "OK";
                        //return setDetail;
                    }
                    else
                    {
                        inserttransaction.Rollback();
                        setDetail.type = "NO";
                        setDetail.message = "操作失败，请重新尝试！";
                        setDetail.wmsObjectDetail = null;
                        return setDetail;
                    }
                    #endregion

                    receving = zgj_order;
                }

                StringBuilder updateString = new StringBuilder(1024);
				//                updateString.Append(@"select a.order_no,a.part_id,a.part_no,a.part_spec,b.qty,b.boxqty,isnull(c.recqty,0) recqty,isnull(c.recboxqty,0) recboxqty,a.enabled  from wms_purchase_detail as a 
				//left join (select part_id,sum(qty) qty,count(1) as boxQty from sys_stock where ref_order_no=@order_no and enabled='Y'  group by part_id ) as b on a.part_id = b.part_id
				//left join (select part_id,sum(qty) recQty,count(1) as recBoxQty from sys_stock where ref_order_no=@order_no and enabled='Y' and status not in (@status20,@status150) group by part_id ) as c on a.part_id=c.part_id
				//where a.order_no=@order_no and a.enabled='Y' order by cast( a.item_no as int)");、
				updateString.Append(@"select a.order_no,a.part_id,a.part_no,a.part_spec,a.qty,b.boxqty,isnull(c.recqty,0) recqty,isnull(c.recboxqty,0) recboxqty,isnull(d.pick_up_tab,0) pick_up_tab,a.enabled,e.instock_type AS IsDirectWarehousing  from wms_purchase_detail as a 
left join (select part_id,sum(qty) qty,count(1) as boxQty,is_direct_warehousing from sys_stock where ref_order_no=@order_no and enabled='Y'  group by part_id,is_direct_warehousing ) as b on a.part_id = b.part_id
left join (select part_id,sum(qty) recQty,count(1) as recBoxQty from sys_stock where ref_order_no=@order_no and enabled='Y' and status not in (@status20,@status150) group by part_id ) as c on a.part_id=c.part_id 
left join (select part_id,count(1) pick_up_tab from sys_stock where ref_order_no=@order_no and enabled='Y' and pick_up_tab='1' and status not in (@status20,@status150) group by part_id ) as d on  a.part_id=d.part_id 
LEFT JOIN dbo.sys_part e ON a.part_id=e.part_id 
 where a.order_no=@order_no and a.enabled='Y' AND e.enabled='Y'    order by cast( a.item_no as int) ");


				DynamicParameters updateStringparameters = new DynamicParameters();
                updateStringparameters.Add("@order_no", receving);
                updateStringparameters.Add("@status20", (int)WmsEnumUtil.StockStatus.WAITING_RECEIVE);
                updateStringparameters.Add("@status150", (int)WmsEnumUtil.StockStatus.REJECTION);
                //通过扫描箱条码，获取对应收货订单
                List<WmsPurchaseDetail> dt = dbConn.Query<WmsPurchaseDetail>(updateString.ToString(), updateStringparameters).ToList();

                if (dt.Count > 0)
                {
                    if (receving.Length > 0)//有订单列表在执行中
                    {
                        //判断是否与当前收货中的订单一致
                        List<WmsPurchaseDetail> Details = dt.Where(a => a.OrderNo == receving && a.Enabled == "Y").ToList();

                        if (Details.Count > 0)
                        {
                            setDetail.type = "OK";
                            setDetail.wmsObjectDetail = dt.ConvertAll(s => (object)s);
                            return setDetail;
                        }
                        else
                        {
                            setDetail.type = "NO";
                            setDetail.message = "[" + cartonNo + "]: 不在此送货单内!";
                            setDetail.wmsObjectDetail = null;
                            return setDetail;
                        }
                    }
                    else
                    {
                        setDetail.type = "OK";
                        setDetail.wmsObjectDetail = dt.ConvertAll(s => (object)s);
                        return setDetail;
                    }
                }
                else
                {
                    //setDetail.type = "NO";
                    //setDetail.message = "未查询到收货订单!";
                    //setDetail.wmsObjectDetail = null;
                    return setDetail;
                }

            }

        }


        /// <summary>
        /// 生成订单编号
        /// </summary>
        /// <returns></returns>
        private string GetOrderNo(string stockOrder, string p)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                DynamicParameters list = new DynamicParameters();
                list.Add("@order_type", stockOrder);
                list.Add("@order_prefix", p);
                list.Add("@order_no", null, DbType.String, ParameterDirection.Output, 50);

                var hashtable = dbConn.Execute("sys_create_orderno", list, commandType: CommandType.StoredProcedure);// this._remotingProxy.ExecuteSotreProcedure("dbo.sys_create_orderno", list);
                string result = list.Get<string>("@order_no");
                return result;
            }
        }

        /// <summary>
        /// 收货选择订单列表
        /// </summary>
        /// <returns></returns>
        public SetObjectDetail GetRecevingListing(string cartonno)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder getCustPartSQL = new StringBuilder(1024);



				//getCustPartSQL.Append(@"select distinct b.order_no,b.* from wms_purchase as a (nolock) 
//left join wms_purchase_detail as b (nolock) on a.order_no = b.order_no
//left join sys_stock as c (nolock) on a.order_no = c.ref_order_no
//where a.order_type = 40 AND (c.status = 25 OR(c.IsDirectWarehousing='1' AND c.status=50 AND (c.IsCreateQcList IS NULL OR c.IsCreateQcList=0 ) )) ");
				//getCustPartSQL.Append(@"select distinct b.order_no,b.* from wms_purchase as a (nolock) 
    //             left join wms_purchase_detail as b (nolock) on a.order_no = b.order_no
    //             where a.order_type = 40  AND a.enabled='Y' ");



				if (cartonno == "" || cartonno == null)
                {
					//getCustPartSQL.Append(@"select  b.order_no,b.* from wms_purchase as a (nolock) 
     //            left join wms_purchase_detail as b (nolock) on a.order_no = b.order_no
     //            where a.order_type = 40  AND a.enabled='Y' and  a.order_status in (10,30) ORDER BY a.create_time desc ");
                    getCustPartSQL.Append(@"select  a.* from wms_purchase as a (nolock) 
                 where a.order_type = 40  AND a.enabled='Y' and  a.order_status in (10,30) ORDER BY a.create_time desc ");
                }
                else
                {
                    //getCustPartSQL.Append(@"select  b.order_no,b.* from wms_purchase as a (nolock) 
                    //            left join wms_purchase_detail as b (nolock) on a.order_no = b.order_no
                    //            where a.order_type = 40  AND a.enabled='Y' and  a.order_status in (10,30)  and a.order_no like '%" + cartonno + "%'  ORDER BY a.create_time desc ");
                    getCustPartSQL.Append(@"select a.* from wms_purchase as a (nolock) 
                 where a.order_type = 40  AND a.enabled='Y' and  a.order_status in (10,30)  and a.order_no like '%" + cartonno + "%'  ORDER BY a.create_time desc ");

                }

				List<WmsPurchase> WmsPurchaseDetail = dbConn.Query<WmsPurchase>(getCustPartSQL.ToString()).ToList();

                SetObjectDetail setDetail = new SetObjectDetail();
                setDetail.type = "OK";
                setDetail.message = "查询成功！";
                setDetail.wmsObjectDetail = WmsPurchaseDetail.ConvertAll(s => (object)s);
                return setDetail;



              
			}
        }
        public SetObjectDetail GetRecevingListByOrderNo(string orderNo,string cartonNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                StringBuilder updateString = new StringBuilder(1024);
                updateString.Append(@"select a.order_no,a.part_id,a.part_no,a.part_spec,a.qty,b.boxqty,isnull(c.recqty,0) recqty,isnull(c.recboxqty,0) recboxqty,isnull(d.pick_up_tab,0) pick_up_tab,a.enabled,e.instock_type AS IsDirectWarehousing  from wms_purchase_detail as a 
left join (select part_id,sum(qty) qty,count(1) as boxQty,is_direct_warehousing from sys_stock where ref_order_no=@order_no and enabled='Y'  group by part_id,is_direct_warehousing ) as b on a.part_id = b.part_id
left join (select part_id,sum(qty) recQty,count(1) as recBoxQty from sys_stock where ref_order_no=@order_no and enabled='Y' and status not in (@status20,@status150) group by part_id ) as c on a.part_id=c.part_id 
left join (select part_id,count(1) pick_up_tab from sys_stock where ref_order_no=@order_no and enabled='Y' and pick_up_tab='1' and status not in (@status20,@status150) group by part_id ) as d on  a.part_id=d.part_id 
LEFT JOIN dbo.sys_part e ON a.part_id=e.part_id 
 where a.order_no=@order_no and a.enabled='Y' AND e.enabled='Y'    order by cast( a.item_no as int) ");

                DynamicParameters updateStringparameters = new DynamicParameters();
                updateStringparameters.Add("@order_no", orderNo);
                updateStringparameters.Add("@status20", (int)WmsEnumUtil.StockStatus.WAITING_RECEIVE);
                updateStringparameters.Add("@status150", (int)WmsEnumUtil.StockStatus.REJECTION);
				//通过扫描箱条码，获取对应收货订单
				//List<WmsPurchaseDetail> dt = dbConn.Query<WmsPurchaseDetail>(updateString.ToString(), updateStringparameters).ToList();

				List<WmsPurchaseDetail_Extend> dt = dbConn.Query<WmsPurchaseDetail_Extend>(updateString.ToString(), updateStringparameters).ToList();


                if (cartonNo.Length > 0)
                {
                    List<string> sqlStrings = new List<string>();
                    List<DynamicParameters> parameterList = new List<DynamicParameters>();
                    for (int i = 0; i < dt.Count; i++)
                    {
                        StringBuilder stringBuilderStock = new StringBuilder(1024);
                        stringBuilderStock.Append(" SELECT * FROM dbo.sys_stock(NOLOCK) WHERE carton_no='" + cartonNo + "'  AND enabled='Y'");
                        List<SysStock_Extend> sysStockPartId = dbConn.Query<SysStock_Extend>(stringBuilderStock.ToString()).ToList();

                        if (sysStockPartId[0].PartNo != dt[i].PartNo)
                        {
                            continue;
                        }


                        StringBuilder stringBuilderPart = new StringBuilder(1024);
                        stringBuilderPart.Append(" SELECT * FROM dbo.sys_part(NOLOCK) WHERE part_id='" + dt[i].PartId + "'  AND enabled='Y'");
                        List<SysPart_Extend> sysParts = dbConn.Query<SysPart_Extend>(stringBuilderPart.ToString()).ToList();


                        // 更新收货明细表：实收数 更新状态：收货中
                        //修改：当零件号的   应收数量  小于等于它的   实收数量 将状态改为40 已完成 否则为 处理中
                        StringBuilder updateString3 = new StringBuilder(1024);
                        decimal revupperQty = 0;//收货上限比
                        decimal revdowmperQty = 0;//收货下限比
                        bool Issql = true;
                        if (sysParts[0].revdowmper > 0 && sysParts[0].revdowmper != null && sysParts[0].revupper > 0 && sysParts[0].revupper != null)
                        {
                            revupperQty = dt[i].Qty * (1 + sysParts[0].revupper);//最多收多少
                            revdowmperQty = dt[i].Qty * (1 - sysParts[0].revdowmper);//最少收多少
                            if (revdowmperQty <= dt[i].RecQty && dt[i].RecQty <= revupperQty)   //收货下限数量<=应收数量<=收货上限数量
                            {
                                updateString3.Append("update wms_purchase_detail set  item_status=40, " +
                                       " rec_qty =@rec_qty  ," +
                                       "rec_box_qty= @rec_box_qty ," +
                                       "update_time=@update_time where order_no=@order_no and part_id=@part_id");

                                Issql = false;

                            }

                        }
                        else if (sysParts[0].revupper > 0 && sysParts[0].revupper != null)//收货上限比。实收数量可以大于应收数量
                        {
                            revupperQty = dt[i].Qty * (1 + sysParts[0].revupper);
                            if (dt[i].Qty <= dt[i].RecQty && dt[i].RecQty <= revupperQty)//应收数量<=实收数量<=收货上限数量
                            {
                                updateString3.Append("update wms_purchase_detail set  item_status=40, " +
                                        "rec_qty =@rec_qty  ," +
                                        "rec_box_qty= @rec_box_qty ," +
                                        "update_time=@update_time where order_no=@order_no and part_id=@part_id");
                                Issql = false;
                            }

                        }
                        else if (sysParts[0].revdowmper > 0 && sysParts[0].revdowmper != null) //收货下限比。应收数量可以小于实收数量
                        {
                            revdowmperQty = dt[i].Qty * (1 - sysParts[0].revdowmper);
                            if (revdowmperQty <= dt[i].RecQty && dt[i].RecQty <= dt[i].Qty)//收货下限数量<=应收数量<=实收数量
                            {
                                updateString3.Append("update wms_purchase_detail set  item_status=40, " +
                                        "rec_qty =@rec_qty  ," +
                                        "rec_box_qty= @rec_box_qty ," +
                                        "update_time=@update_time where order_no=@order_no and part_id=@part_id");
                                Issql = false;
                            }

                        }
                        else //应收数量=实收数量
                        {
                            if (dt[i].RecQty == dt[i].Qty)//收货下限数量<=应收数量<=实收数量
                            {
                                updateString3.Append("update wms_purchase_detail set  item_status=40, " +
                                        "rec_qty =@rec_qty  ," +
                                        "rec_box_qty= @rec_box_qty ," +
                                        "update_time=@update_time where order_no=@order_no and part_id=@part_id");
                                Issql = false;
                            }
                        }

                        if (Issql)
                        {
                            updateString3.Append("update wms_purchase_detail set  item_status=30, " +
                                       "rec_qty =@rec_qty  ," +
                                       "rec_box_qty= @rec_box_qty ," +
                                       "update_time=@update_time where order_no=@order_no and part_id=@part_id");
                        }



                        DynamicParameters updateStringparameters3 = new DynamicParameters();
                        updateStringparameters3.Add("@order_no", orderNo);
                        updateStringparameters3.Add("@rec_qty", dt[i].RecQty);
                        updateStringparameters3.Add("@rec_box_qty", dt[i].RecBoxQty);
                        updateStringparameters3.Add("@part_id", dt[i].PartId);
                        updateStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

                        sqlStrings.Add(updateString3.ToString());
                        parameterList.Add(updateStringparameters3);

                    }

                    IDbTransaction transaction = dbConn.BeginTransaction();

                    bool successCount = true;
                    for (int i = 0; i < sqlStrings.Count; i++)
                    {
                        if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
                        {
                            successCount = false;
                        }
                    }
                    if (successCount)
                    {
                        transaction.Commit();
                    }
                    else
                    {
                        transaction.Rollback();
                    }
                }

				






				SetObjectDetail setDetail = new SetObjectDetail();
                setDetail.type = "OK";
                setDetail.message = "查询成功！";
                setDetail.wmsObjectDetail = dt.ConvertAll(s => (object)s);
                return setDetail;
            }
        }

        public SetObjectDetail GetRealOrderList(string orderNo)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                StringBuilder updateString = new StringBuilder(1024);
                updateString.Append(@"select * from sys_stock where ref_order_no =@order_no and enabled ='Y' order by status ");

                DynamicParameters updateStringparameters = new DynamicParameters();
                updateStringparameters.Add("@order_no", orderNo);
                //通过扫描箱条码，获取对应收货订单
                List<SysStock> dt = dbConn.Query<SysStock>(updateString.ToString(), updateStringparameters).ToList();

                SetObjectDetail setDetail = new SetObjectDetail();
                setDetail.type = "OK";
                setDetail.message = "查询成功！";
                setDetail.wmsObjectDetail = dt.ConvertAll(s => (object)s);
                return setDetail;
            }
        }


        /// <summary>
        /// 生成质检单
        /// </summary>
        /// <param name="receving"></param>
        /// <param name="loginId"></param>
        /// <returns></returns>
        public string CreateQcInfo(string receving, string loginId)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

				#region 注释

				//				StringBuilder _WmsPurchaseDetailString = new StringBuilder(1024);
				//				_WmsPurchaseDetailString.Append(@"select a.order_no,a.part_id,a.part_no,a.part_spec,a.qty,b.boxqty,isnull(c.recqty,0) recqty,isnull(c.recboxqty,0) recboxqty,isnull(d.pick_up_tab,0) pick_up_tab,a.enabled,e.instock_type AS IsDirectWarehousing  from wms_purchase_detail as a 
				//left join (select part_id,sum(qty) qty,count(1) as boxQty,IsDirectWarehousing from sys_stock where ref_order_no=@order_no and enabled='Y'  group by part_id,IsDirectWarehousing ) as b on a.part_id = b.part_id
				//left join (select part_id,sum(qty) recQty,count(1) as recBoxQty from sys_stock where ref_order_no=@order_no and enabled='Y' and status not in (@status20,@status150) group by part_id ) as c on a.part_id=c.part_id 
				//left join (select part_id,count(1) pick_up_tab from sys_stock where ref_order_no=@order_no and enabled='Y' and pick_up_tab='1' and status not in (@status20,@status150) group by part_id ) as d on  a.part_id=d.part_id 
				//LEFT JOIN dbo.sys_part e ON a.part_id=e.part_id 
				// where a.order_no=@order_no and a.enabled='Y' AND e.enabled='Y'    order by cast( a.item_no as int) ");

				//				DynamicParameters updateStringparameters = new DynamicParameters();
				//				updateStringparameters.Add("@order_no", receving);
				//				updateStringparameters.Add("@status20", (int)WmsEnumUtil.StockStatus.WAITING_RECEIVE);
				//				updateStringparameters.Add("@status150", (int)WmsEnumUtil.StockStatus.REJECTION);
				//				//通过扫描箱条码，获取对应收货订单
				//				//List<WmsPurchaseDetail> dt = dbConn.Query<WmsPurchaseDetail>(updateString.ToString(), updateStringparameters).ToList();

				//				List<WmsPurchaseDetail_Extend> wmsPurchaseDetail = dbConn.Query<WmsPurchaseDetail_Extend>(_WmsPurchaseDetailString.ToString(), updateStringparameters).ToList();

				//				List<string> sqlStrings = new List<string>();
				//				List<DynamicParameters> parameterList = new List<DynamicParameters>();

				//				if (wmsPurchaseDetail.Count>0)
				//                {
				//                    var qtySum = wmsPurchaseDetail.Sum(s => s.Qty);//应收数量
				//                    var recQtySum = wmsPurchaseDetail.Sum(s => s.RecQty);//实收数量
				//                    var boxqtySum = wmsPurchaseDetail.Sum(s => s.BoxQty);//应收箱数
				//                    var recboxqtySum = wmsPurchaseDetail.Sum(s => s.RecBoxQty);//实收箱数

				//                    if (qtySum == recQtySum && boxqtySum == recboxqtySum)//满足条件生成质检单时
				//                    {
				//                        StringBuilder GetQcSql = new StringBuilder(1024);
				//                        // GetQcSql.Append("select * from sys_stock where ref_order_no = @ref_order_no and status = 25 ");
				//                        GetQcSql.Append("select a.*,b.is_exemption from sys_stock a LEFT JOIN sys_part b ON a.part_id=b.part_id  WHERE a.ref_order_no = '@ref_order_no' "
				//                            + "  and a.enabled='Y' AND b.enabled='Y' and (a.status = 25 OR  ( a.status=50 AND a.IsDirectWarehousing=1 AND  (a.IsCreateQcList=0 or a.IsCreateQcList is null)))");

				//                        DynamicParameters Qcparameters = new DynamicParameters();
				//                        Qcparameters.Add("@ref_order_no", receving);
				//                        List<SysStock_Extend> GetQcList = dbConn.Query<SysStock_Extend>(GetQcSql.ToString(), Qcparameters).ToList();

				//                        List<SysStock_Extend> _GetNQcList = GetQcList.Where(s => s.IsExemption == "0").ToList();//免检
				//                        List<SysStock_Extend> __GetQcList = GetQcList.Where(s => s.IsExemption == "1").ToList();//质检



				//                        //生成质检单号
				//                        string QcOrder = GetOrderNo("QCList", "QC");
				//                        string prove = QcOrder.Substring(4);

				//                        //将需要生成质检单的零件分组求和
				//                        List<SysStock_Extend> GetQcListSum = __GetQcList.GroupBy(a => a.PartNo).Select(b => new SysStock_Extend
				//                        {
				//                            PartNo = b.Key,
				//                            Qty = b.Sum(b2 => b2.Qty)
				//                        }).ToList();

				//                        List<WmsPurchase> getorder = GetWmsPurchaseInfo(GetQcList[0].RefOrderNo);
				//                        if (GetQcListSum.Count > 0)//需要质检的
				//                        {

				//                            for (int i = 0; i < GetQcListSum.Count; i++)
				//                            {
				//                                StringBuilder insertSAPQC = new StringBuilder(1024);
				//                                #region 注释
				//                                //insertSAPQC.Append(@" INSERT INTO [dbo].[WMS_TOQC]
				//                                //                  ([BSTYP]
				//                                //                  ,[EVRTN]
				//                                //                  ,[ETENR]
				//                                //                  ,[QCNUM]
				//                                //                  ,[LGORT]
				//                                //                  ,[UNIT]
				//                                //                  ,[ZPOST]
				//                                //                  ,[ZTIME]
				//                                //                  ,[WERKS]
				//                                //                  ,[MATNR]
				//                                //                  ,[LIFNR]
				//                                //                  ,[QCOPERATOR]
				//                                //                  ,[LOTON]
				//                                //                  ,[ISQCCOM]
				//                                //                  ,[SID]
				//                                //                  ,[ACTTIM]
				//                                //                  ,[ACTUSR],[STAFLG])
				//                                //                    VALUES(
				//                                //                    @BSTYP,@EVRTN,@ETENR,@QCNUM,
				//                                //                    @LGORT,@UNIT,@ZPOST,@ZTIME,@WERKS,@MATNR,@LIFNR,
				//                                //                    @QCOPERATOR，@LOTON,@ISQCCOM,
				//                                //                    @SID,@ACTTIM,@ACTUSR,@STAFLG,)");

				//                                //DynamicParameters insertSAPQCparameters = new DynamicParameters();
				//                                //insertSAPQCparameters.Add("@BSTYP", "1");//getorder[0].OrderType == (int)WmsEnumUtil.PurchaseOrderType.PO ? "F" : "L"// 单据类型 1来料质检，2生产质检，3委外检验单    待确认   
				//                                //insertSAPQCparameters.Add("@EVRTN", getorder[0].OrderNo.Trim());
				//                                //insertSAPQCparameters.Add("@ETENR", QcOrder);//getItemNo(getorder[0].OrderNo, GetQcListSumList[i].PartNo)[0].ItemNo
				//                                //insertSAPQCparameters.Add("@QCNUM", GetQcListSum[i].Qty);
				//                                //insertSAPQCparameters.Add("@LGORT", GetQcListSum[i].LocateName);//getItemNo(getorder[0].OrderNo, GetQcListSum[i].PartNo)[0].ErpWarehouse
				//                                //insertSAPQCparameters.Add("@UNIT", getPart(GetQcListSum[i].PartNo)[0].Unit);
				//                                //insertSAPQCparameters.Add("@ZPOST", DateTime.Now.ToString("yyyyMMdd"));
				//                                //insertSAPQCparameters.Add("@ZTIME", DateTime.Now.ToString("HHmmss"));
				//                                //insertSAPQCparameters.Add("@WERKS", getorder[0].FactoryCode);
				//                                //insertSAPQCparameters.Add("@MATNR", GetQcListSum[i].PartNo);
				//                                //insertSAPQCparameters.Add("@LIFNR", getorder[0].VendorCode);
				//                                //insertSAPQCparameters.Add("@QCOPERATOR", " ");//质检操作人  待确认
				//                                //insertSAPQCparameters.Add("@LOTON", GetQcListSum[0].LotNo);
				//                                //insertSAPQCparameters.Add("@ISQCCOM", "0");//质检标识  是否完成质检  待确认
				//                                //insertSAPQCparameters.Add("@SID", Guid.NewGuid().ToString().Replace("-", ""));
				//                                //insertSAPQCparameters.Add("@ACTTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
				//                                //insertSAPQCparameters.Add("@ACTUSR", loginId);
				//                                //insertSAPQCparameters.Add("@STAFLG", "0"); //状态标志   待确认
				//                                #endregion


				//                                insertSAPQC.Append(@" INSERT INTO [dbo].[WMS_TOQC]
				//                                          ([BSTYP]
				//                                          ,[EVRTN]
				//                                          ,[ISQCCOM]
				//                                          ,[ETENR]
				//                                          ,[LIFNR]
				//                                          ,[PARTNO]
				//                                          ,[PARTNONUM]
				//                                          ,[LOTON]
				//                                          ,[SID]
				//                                          ,[ACTTIM]
				//                                          ,[ACTUSR],[STAFLG])
				//                                            VALUES(
				//                                            @BSTYP,@EVRTN,@ISQCCOM,@ETENR,
				//                                            @LIFNR,@PARTNO,@PARTNONUM,@LOTON,
				//                                            @SID,@ACTTIM,@ACTUSR,@STAFLG,)");

				//                                DynamicParameters insertSAPQCparameters = new DynamicParameters();
				//                                insertSAPQCparameters.Add("@BSTYP", "1");//单据类型     1来料质检，2生产质检，3委外检验单
				//								insertSAPQCparameters.Add("@EVRTN", getorder[0].OrderNo.Trim());//关联单号
				//								insertSAPQCparameters.Add("@ISQCCOM", "Y");//质检通知标识     Y:需要质检
				//								insertSAPQCparameters.Add("@ETENR", QcOrder);//单号 qc单号
				//								insertSAPQCparameters.Add("@LIFNR", getorder[0].VendorCode);//供应商代码
				//								insertSAPQCparameters.Add("@PARTNO", GetQcListSum[i].PartNo);//零件号
				//								insertSAPQCparameters.Add("@PARTNONUM", GetQcListSum[i].Qty);//零件数量
				//								insertSAPQCparameters.Add("@LOTON", GetQcListSum[0].LotNo);//批次
				//								insertSAPQCparameters.Add("@SID", Guid.NewGuid().ToString().Replace("-", ""));
				//                                insertSAPQCparameters.Add("@ACTTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//处理日期
				//								insertSAPQCparameters.Add("@ACTUSR", loginId);//处理人
				//								insertSAPQCparameters.Add("@STAFLG", "0"); //状态标志   待确认

				//								sqlStrings.Add(insertSAPQC.ToString());
				//                                parameterList.Add(insertSAPQCparameters);


				//                                //并且在 GetQcList 需要生成质检单的箱条码列表中去掉
				//                                //GetQcList.RemoveAll(s => s.PartNo == GetQcListSum[i].PartNo);

				//                            }

				//                        }

				//                        if (__GetQcList.Count > 0)
				//                        {
				//                            for (int i = 0; i < __GetQcList.Count; i++)
				//                            {
				//                                //更新条码表，直接变为 30 待质检
				//                                StringBuilder qcUpdateString = new StringBuilder(1024);
				//                                if (GetQcList[0].IsDirectWarehousing == "1")//判断单子是否直入库
				//                                {
				//                                    //直入库
				//                                    qcUpdateString.Append(@"update sys_stock set IsCreateQcList=0,pick_up_tab='0' where ref_order_no=@ref_order_no and status = 50 and carton_no=@carton_no ");//IsCreateQcList ：是否完成了质检，0：未质检，1：已质检
				//                                }
				//                                else
				//                                {
				//                                    qcUpdateString.Append(@"update sys_stock set status='30',pick_up_tab='0' where ref_order_no=@ref_order_no and status = 25 and carton_no=@carton_no ");
				//                                }
				//                                DynamicParameters qcUpdateStringparameters = new DynamicParameters();
				//                                qcUpdateStringparameters.Add("@ref_order_no", getorder[0].OrderNo);
				//                                qcUpdateStringparameters.Add("@carton_no", __GetQcList[i].CartonNo);
				//                                sqlStrings.Add(qcUpdateString.ToString());
				//                                parameterList.Add(qcUpdateStringparameters);
				//                            }

				//                        }


				//                        if (_GetNQcList.Count > 0)
				//                        {


				//                            //不用质检，直接入库
				//                            // 更新条码表，直接变为 40 待入库
				//                            StringBuilder _updateString = new StringBuilder(1024);
				//                            if (GetQcList[0].IsDirectWarehousing == "1")//判断单子是否直入库
				//                            {
				//                                //直入库
				//                                _updateString.Append("update sys_stock set status='50' ,IsCreateQcList=1 where ref_order_no=@ref_order_no and status = 50 and carton_no=@carton_no ");
				//                            }
				//                            else
				//                            {
				//                                _updateString.Append("update sys_stock set status='40' where ref_order_no=@ref_order_no and status = 25 and carton_no=@carton_no ");
				//                            }
				//                            DynamicParameters _updateStringparameters = new DynamicParameters();
				//                            _updateStringparameters.Add("@ref_order_no", getorder[0].OrderNo);
				//                            _updateStringparameters.Add("@carton_no", _GetNQcList[0].CartonNo);
				//                            sqlStrings.Add(_updateString.ToString());
				//                            parameterList.Add(_updateStringparameters);

				//                        }




				//                    }
				//                    else if (qtySum > recQtySum && boxqtySum < recboxqtySum)//确认收货，但不会生成质检单
				//                    {
				//                        return "OK";
				//                    }
				//                    else
				//                    {
				//                        if (qtySum < recQtySum)
				//                        {
				//							return "实数数量，大于了应收数量，请修改数量！";
				//						}
				//                    }

				//					//执行事务
				//					IDbTransaction transaction = dbConn.BeginTransaction();

				//					bool successCount = true;
				//					for (int i = 0; i < sqlStrings.Count; i++)
				//					{
				//						if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
				//						{
				//							successCount = false;
				//						}
				//					}
				//					//return "OK";
				//					if (successCount)
				//					{
				//						transaction.Commit();
				//						return "OK";
				//					}
				//					else
				//					{
				//						transaction.Rollback();
				//						return "操作失败，请重新尝试！";
				//					}
				//				}
				//                else
				//                {
				//					return "没有订单，不可生成质检单";
				//				}


				#endregion


				#region 原先的代码逻辑

				//判断箱条码是否已存在
				StringBuilder GetQcSql = new StringBuilder(1024);
                // GetQcSql.Append("select * from sys_stock where ref_order_no = @ref_order_no and status = 25 ");
                //GetQcSql.Append("select * from sys_stock where ref_order_no = @ref_order_no  and enabled='Y' and (status = 25 OR  ( status=50 AND IsDirectWarehousing=1 AND  (IsCreateQcList=0 or IsCreateQcList is null)))");
                GetQcSql.Append("select a.* ,b.instock_type AS IsDirectWarehousing  from sys_stock a LEFT JOIN dbo.sys_part b ON a.part_id=b.part_id WHERE a.ref_order_no = @ref_order_no  and a.enabled='Y' AND (a.status = 25 OR  ( a.status=50 AND b.instock_type=1 AND  (a.is_create_qc_list=0 or a.is_create_qc_list is null)))");


                DynamicParameters Qcparameters = new DynamicParameters();
                Qcparameters.Add("@ref_order_no", receving);
                List<SysStock_Extend> GetQcList = dbConn.Query<SysStock_Extend>(GetQcSql.ToString(), Qcparameters).ToList();



                List<string> sqlStrings = new List<string>();
                List<DynamicParameters> parameterList = new List<DynamicParameters>();

                #region 修改收货主表
                //判断订单是否收货完成
                StringBuilder Ischeckpurchase = new StringBuilder(1024);
                DynamicParameters Ischeckpurchaseparameters = new DynamicParameters();
				//Ischeckpurchase.Append(@"select * from wms_purchase_detail  where order_no = @order_no and item_status=@item_status");
				Ischeckpurchase.Append(@"select * from wms_purchase_detail  where order_no = @order_no ");
				//Ischeckpurchaseparameters.Add("@item_status", (int)WmsEnumUtil.PurchaseOrderDetailStatus.COMPLETED);
                Ischeckpurchaseparameters.Add("@order_no", receving);

                List<WmsPurchaseDetail> CheckPurchaseList = dbConn.Query<WmsPurchaseDetail>(Ischeckpurchase.ToString(), Ischeckpurchaseparameters).ToList();
                var x = CheckPurchaseList.Sum(a => a.ItemStatus);

                if (CheckPurchaseList.Count * 40 == x)
                {
                    //修改明细表
                    //更新收货表
                    StringBuilder COMPLETEDString = new StringBuilder(1024);
                    COMPLETEDString.Append(@" update wms_purchase set order_status=@order_status,update_userid=@update_userid,update_time=@update_time where order_no = @order_no");
                    DynamicParameters COMPLETEDStringparameters = new DynamicParameters();
                    COMPLETEDStringparameters.Add("@order_no", receving);
                    COMPLETEDStringparameters.Add("@order_status", (int)WmsEnumUtil.PurchaseOrderStatus.COMPLETED);
                    COMPLETEDStringparameters.Add("@update_userid", loginId);
                    COMPLETEDStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    //dbConn.Execute(COMPLETEDString.ToString(), COMPLETEDStringparameters);
                    sqlStrings.Add(COMPLETEDString.ToString());
                    parameterList.Add(COMPLETEDStringparameters);
                }
                #endregion



                //生成质检单号
                string _QcOrder = GetOrderNo("QCList", "QC");
                string QcOrder = _QcOrder.Trim().ToString();//去掉空格

				string prove = QcOrder.Substring(4);

				
				//判断免检清单
				if (GetQcList.Count > 0)
                {
                    //查询免检物料清单
                    StringBuilder exemptionString = new StringBuilder(1024);
                    exemptionString.Append(" select part_no from sys_exemption_list  where enabled='Y' ");
                    List<string> exemptionList = dbConn.Query<string>(exemptionString.ToString()).ToList();

                    //将需要生成质检单的零件分组求和
                    List<SysStock> GetQcListSum = GetQcList.GroupBy(a => a.PartNo).Select(b => new SysStock
                    {
                        PartNo = b.Key,
                        Qty = b.Sum(b2 => b2.Qty)
                    }).ToList();
                    //判断是否在免检清单里
                    List<SysStock> GetQcListSumList = GetQcListSum.Where(a => exemptionList.Contains(a.PartNo)).ToList();

                    if (GetQcListSumList.Count > 0)
                    {
                        List<WmsPurchase> getorder = GetWmsPurchaseInfo(GetQcList[0].RefOrderNo);
                        for (int i = 0; i < GetQcListSumList.Count; i++)
                        {
                            //StringBuilder insertSAPQC = new StringBuilder(1024);
                            //insertSAPQC.Append(@" INSERT INTO [dbo].[WMS_INQC]
                            //                              ([BSTYP]
                            //                              ,[EVRTN]
                            //                              ,[ETENR]
                            //                              ,[ZDEV]
                            //                              ,[LGORT]
                            //                              ,[UNIT]
                            //                              ,[ZPOST]
                            //                              ,[ZTIME]
                            //                              ,[WERKS]
                            //                              ,[MATNR]
                            //                              ,[LIFNR]
                            //                              ,[SID]
                            //                              ,[ACTTIM]
                            //                              ,[ACTUSR],[prove])
                            //                                VALUES(@BSTYP,@EVRTN,@ETENR,@ZDEV,@LGORT,@UNIT,@ZPOST,@ZTIME,@WERKS,@MATNR,@LIFNR,@SID,@ACTTIM,@ACTUSR,@prove)");

                            //DynamicParameters insertSAPQCparameters = new DynamicParameters();
                            //insertSAPQCparameters.Add("@BSTYP", getorder[0].OrderType == (int)WmsEnumUtil.PurchaseOrderType.PO ? "F" : "L");
                            //insertSAPQCparameters.Add("@EVRTN", getorder[0].OrderNo.Trim());
                            //insertSAPQCparameters.Add("@SID", Guid.NewGuid().ToString().Replace("-", ""));
                            //insertSAPQCparameters.Add("@ETENR", getItemNo(getorder[0].OrderNo, GetQcListSumList[i].PartNo)[0].ItemNo);
                            //insertSAPQCparameters.Add("@ZDEV", GetQcListSumList[i].Qty);
                            //insertSAPQCparameters.Add("@LGORT", getItemNo(getorder[0].OrderNo, GetQcListSumList[i].PartNo)[0].ErpWarehouse);
                            //insertSAPQCparameters.Add("@UNIT", getPart(GetQcListSumList[i].PartNo)[0].Unit);
                            //insertSAPQCparameters.Add("@ACTTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            //insertSAPQCparameters.Add("@ACTUSR", loginId);
                            //insertSAPQCparameters.Add("@ZPOST", DateTime.Now.ToString("yyyyMMdd"));
                            //insertSAPQCparameters.Add("@ZTIME", DateTime.Now.ToString("HHmmss"));
                            //insertSAPQCparameters.Add("@WERKS", getorder[0].FactoryCode);
                            //insertSAPQCparameters.Add("@MATNR", GetQcListSumList[i].PartNo);
                            //insertSAPQCparameters.Add("@LIFNR", getorder[0].VendorCode);
                            //insertSAPQCparameters.Add("@prove", prove);

                            //sqlStrings.Add(insertSAPQC.ToString());
                            //parameterList.Add(insertSAPQCparameters);

                            //更新条码表，直接变为 40 待入库
                            StringBuilder updateString = new StringBuilder(1024);
                            if (GetQcList[0].IsDirectWarehousing == "1")//判断单子是否直入库
                            {
                                //直入库
                                updateString.Append("update sys_stock set status='50', is_create_qc_list=1 where ref_order_no=@ref_order_no and status = 50 and part_no=@part_no ");
                            }
                            else
                            {
                                updateString.Append("update sys_stock set status='40'  where ref_order_no=@ref_order_no and status = 25 and part_no=@part_no ");
                            }
                            DynamicParameters updateStringparameters = new DynamicParameters();
                            updateStringparameters.Add("@ref_order_no", getorder[0].OrderNo);
                            updateStringparameters.Add("@part_no", GetQcListSumList[i].PartNo);
                            sqlStrings.Add(updateString.ToString());
                            parameterList.Add(updateStringparameters);

                            //并且在 GetQcList 需要生成质检单的箱条码列表中去掉
                            GetQcList.RemoveAll(s => s.PartNo == GetQcListSumList[i].PartNo);
                        }

                    }
                }


                if (GetQcList.Count > 0)
                {

                    #region 新增质检表

                    StringBuilder insertString = new StringBuilder(1024);
                    insertString.Append(@"INSERT INTO [dbo].[wms_qc_header]
                                                        ([order_no]
                                                        ,[vendor_id]
                                                        ,[vendor_code]
                                                        ,[order_status]
                                                        ,[ref_order_no]
                                                        ,[remark]
                                                        ,[factory_id]
                                                        ,[factory_code]
                                                        ,[enabled]
                                                        ,[create_userid]
                                                        ,[create_time]
                                                        ,[update_userid]
                                                        ,[update_time]
                                                        ,[guid])
                                                          VALUES  (@order_no,@vendor_id,@vendor_code,@order_status,@ref_order_no,@remark,@factory_id,@factory_code,@enabled,@create_userid
                ,@create_time,@update_userid,@update_time,@guid)");

                    DynamicParameters insertStringparameters = new DynamicParameters();
                    insertStringparameters.Add("@order_no", QcOrder);
                    insertStringparameters.Add("@vendor_id", GetQcList[0].VendorId);
                    insertStringparameters.Add("@vendor_code", GetQcList[0].VendorCode);
                    insertStringparameters.Add("@order_status", 10);
                    insertStringparameters.Add("@ref_order_no", receving);
                    insertStringparameters.Add("@remark", "");
                    insertStringparameters.Add("@factory_id", GetQcList[0].FactoryId);
                    insertStringparameters.Add("@factory_code", GetQcList[0].FactoryCode);
                    insertStringparameters.Add("@enabled", "Y");
                    insertStringparameters.Add("@update_userid", loginId);
                    insertStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    insertStringparameters.Add("@create_userid", loginId);
                    insertStringparameters.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    insertStringparameters.Add("@guid", Guid.NewGuid());

                    sqlStrings.Add(insertString.ToString());
                    parameterList.Add(insertStringparameters);

                    #endregion

                    for (int i = 0; i < GetQcList.Count; i++)
                    {
                        #region 新增质检明细表
                        StringBuilder insertString2 = new StringBuilder(1024);
                        insertString2.Append(@"INSERT INTO [dbo].[wms_qc_detail]
                                                             ([order_no]
                                                             ,[part_id]
                                                             ,[part_no]
                                                             ,[part_spec]
                                                             ,[carton_no]
                                                             ,[lot_no]
                                                             ,[qty]
                                                             ,[nc_qty]
                                                             ,[item_status]
                                                             ,[remark]
                                                             ,[factory_id]
                                                             ,[factory_code]
                                                             ,[enabled]
                                                             ,[create_userid]
                                                             ,[create_time]
                                                             ,[update_userid]
                                                             ,[update_time]
                                                             ,[guid])
                                                            VALUES (@order_no,@part_id,@part_no,@part_spec,@carton_no,@lot_no,@qty,@nc_qty,@item_status,@remark,@factory_id,@factory_code
                ,@enabled,@create_userid,@create_time,@update_userid,@update_time,@guid) ");

                        DynamicParameters insertStringparameters2 = new DynamicParameters();
                        insertStringparameters2.Add("@order_no", QcOrder);
                        insertStringparameters2.Add("@part_id", GetQcList[i].PartId);
                        insertStringparameters2.Add("@part_no", GetQcList[i].PartNo);
                        insertStringparameters2.Add("@part_spec", GetQcList[i].PartSpec);
                        insertStringparameters2.Add("@carton_no", GetQcList[i].CartonNo);
                        insertStringparameters2.Add("@lot_no", GetQcList[i].LotNo);
                        insertStringparameters2.Add("@qty", GetQcList[i].Qty);
                        insertStringparameters2.Add("@nc_qty", "0");
                        insertStringparameters2.Add("@item_status", 10);
                        insertStringparameters2.Add("@remark", null);
                        insertStringparameters2.Add("@factory_id", GetQcList[i].FactoryId);
                        insertStringparameters2.Add("@factory_code", GetQcList[i].FactoryCode);
                        insertStringparameters2.Add("@enabled", "Y");
                        insertStringparameters2.Add("@update_userid", loginId);
                        insertStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        insertStringparameters2.Add("@create_userid", loginId);
                        insertStringparameters2.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        insertStringparameters2.Add("@guid", Guid.NewGuid());
                        sqlStrings.Add(insertString2.ToString());
                        parameterList.Add(insertStringparameters2);

                        #endregion

                        #region 修改库存表状态 25 为 30或 50

                        StringBuilder updateString = new StringBuilder(1024);
                        if (GetQcList[0].IsDirectWarehousing == "1")//判断单子是否直入库
                        {
                            updateString.Append(@"update sys_stock set status='50', is_create_qc_list=0,pick_up_tab='0' where guid=@guid ");//IsCreateQcList ：是否完成了质检，0：未质检，1：已质检
                        }
                        else
                        {
                            updateString.Append(@"update sys_stock set status='30',pick_up_tab='0' where guid=@guid ");
                        }

                        DynamicParameters updateStringparameters = new DynamicParameters();
                        updateStringparameters.Add("@guid", GetQcList[i].Guid);
                        sqlStrings.Add(updateString.ToString());
                        parameterList.Add(updateStringparameters);

						#endregion



					}


					//将需要生成质检单的零件分组求和
					List<SysStock> _GetQcListSum = GetQcList.GroupBy(a => a.PartNo).Select(b => new SysStock
					{
						PartNo = b.Key,
						Qty = b.Sum(b2 => b2.Qty)
					}).ToList();

					List<WmsPurchase> getorder = GetWmsPurchaseInfo(GetQcList[0].RefOrderNo);

                    for (int i = 0; i < _GetQcListSum.Count; i++)
                    {
                        #region 插入接口表
                        List<WmsPurchaseDetail> getorderDetail = new List<WmsPurchaseDetail>();

						if (getorder.Count() > 0)
                        {
							getorderDetail = getItemNo(getorder[0].OrderNo, _GetQcListSum[0].PartNo);
						}
					

						StringBuilder insertSAPQC = new StringBuilder(1024);

						insertSAPQC.Append(@" INSERT INTO [dbo].[WMS_TOQC]
                                                            ([BSTYP]  
                                                            ,[EVRTN]
                                                            ,[EVRTNLINE]
                                                            ,[ISQCCOM]
                                                            ,[ETENR]
                                                            ,[QCNUM]
                                                            ,[PART_NO]
                                                            ,[ZDEV]
                                                            ,[NZDEV]
                                                            ,[UNIT]
                                                            ,[ZPOST]
                                                            ,[ZTIME]
                                                            ,[WERKS]
                                                            ,[LIFNR]
                                                            ,[QCOPERATOR]
                                                            ,[LOTON]
                                                            ,[SID],[ACTTIM],[ACTUSR],[STAFLG] )
                                                          VALUES(
                                                            @BSTYP,@EVRTN,@EVRTNLINE,@ISQCCOM,@ETENR,@QCNUM,
				                                            @PARTNO,@ZDEV,@NZDEV,@UNIT,@ZPOST,@ZTIME,@WERKS,
                                                            @LIFNR,@QCOPERATOR,@LOTON,
				                                            @SID,@ACTTIM,@ACTUSR,@STAFLG)");

                        DynamicParameters insertSAPQCparameters = new DynamicParameters();
                        insertSAPQCparameters.Add("@BSTYP", "1");//单据类型     1来料质检，2生产质检，3委外检验单
                        insertSAPQCparameters.Add("@EVRTN", GetQcList[0].RelevanceOrder.Length == 0 ? "" : GetQcList[0].RelevanceOrder); //GetQcList[0].RecCartonQty.Trim()//关联单号  收料通知单
						insertSAPQCparameters.Add("@EVRTNLINE", (getorderDetail.Count > 0)? getorderDetail[0].ItemNo:"0");//关联单据中该物料所在行号                         
						insertSAPQCparameters.Add("@ISQCCOM", "Y");//质检通知标识     Y:需要质检
                        insertSAPQCparameters.Add("@ETENR", QcOrder);//单号 qc单号
						insertSAPQCparameters.Add("@QCNUM", _GetQcListSum[i].Qty);//应质检数量
						insertSAPQCparameters.Add("@PARTNO", _GetQcListSum[i].PartNo);//零件号
						insertSAPQCparameters.Add("@ZDEV", 0);//合格数量
						insertSAPQCparameters.Add("@NZDEV", 0);//不合格数量
						insertSAPQCparameters.Add("@UNIT", _GetQcListSum[i].Unit);//计量单位
						insertSAPQCparameters.Add("@ZPOST", DateTime.Now.ToString("yyyy-MM-dd"));//操作日期
						insertSAPQCparameters.Add("@ZTIME", DateTime.Now.ToString("HH:mm:ss"));//操作时间
						insertSAPQCparameters.Add("@WERKS", GetQcList[0].FactoryId);//收货工厂
						insertSAPQCparameters.Add("@LIFNR", getorder[0].VendorCode);//供应商代码
						insertSAPQCparameters.Add("@QCOPERATOR", loginId);//质检操作人
						insertSAPQCparameters.Add("@LOTON", GetQcList[0].LotNo);//批次
                        insertSAPQCparameters.Add("@SID", Guid.NewGuid().ToString().Replace("-", ""));
                        insertSAPQCparameters.Add("@ACTTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//处理日期
                        insertSAPQCparameters.Add("@ACTUSR", loginId);//处理人
                        insertSAPQCparameters.Add("@STAFLG", "0"); //状态标志   待确认
						sqlStrings.Add(insertSAPQC.ToString());
						parameterList.Add(insertSAPQCparameters);

						//insertSAPQC.Append(@" INSERT INTO [dbo].[WMS_TOQCE]
						//                                        ([BSTYP]
						//                                        ,[EVRTN]
						//                                        ,[ISQCCOM]
						//                                        ,[ETENR]
						//                                        ,[LIFNR]
						//                                        ,[PARTNO]
						//                                        ,[PARTNONUM]
						//                                        ,[LOTON]
						//                                        ,[SID]
						//                                        ,[ACTTIM]
						//                                        ,[ACTUSR],[STAFLG])
						//                                          VALUES(
						//                                          @BSTYP,@EVRTN,@ISQCCOM,@ETENR,
						//                                          @LIFNR,@PARTNO,@PARTNONUM,@LOTON,
						//                                          @SID,@ACTTIM,@ACTUSR,@STAFLG)");

						//DynamicParameters insertSAPQCparameters = new DynamicParameters();
						//insertSAPQCparameters.Add("@BSTYP", "1");//单据类型     1来料质检，2生产质检，3委外检验单
						//insertSAPQCparameters.Add("@EVRTN", GetQcList[0].RelevanceOrder.Length==0?"": GetQcList[0].RelevanceOrder); //GetQcList[0].RecCartonQty.Trim()//关联单号
						//insertSAPQCparameters.Add("@ISQCCOM", "Y");//质检通知标识     Y:需要质检
						//insertSAPQCparameters.Add("@ETENR", QcOrder);//单号 qc单号
						//insertSAPQCparameters.Add("@LIFNR", getorder[0].VendorCode);//供应商代码
						//insertSAPQCparameters.Add("@PARTNO", _GetQcListSum[i].PartNo);//零件号
						//insertSAPQCparameters.Add("@PARTNONUM", _GetQcListSum[i].Qty);//零件数量
						//insertSAPQCparameters.Add("@LOTON", GetQcList[0].LotNo);//批次
						//insertSAPQCparameters.Add("@SID", Guid.NewGuid().ToString().Replace("-", ""));
						//insertSAPQCparameters.Add("@ACTTIM", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//处理日期
						//insertSAPQCparameters.Add("@ACTUSR", loginId);//处理人
						//insertSAPQCparameters.Add("@STAFLG", "0"); //状态标志   待确认

						//                  sqlStrings.Add(insertSAPQC.ToString());
						//parameterList.Add(insertSAPQCparameters);

						#endregion


					}

                }

                #endregion

                #region 执行事务

                //执行事务
                IDbTransaction transaction = dbConn.BeginTransaction();

                bool successCount = true;
                for (int i = 0; i < sqlStrings.Count; i++)
                {
                    if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
                    {
                        successCount = false;
                    }
                }
                

                //return "OK";
                if (successCount)
                {
                    transaction.Commit();

                    if (GetQcList.Count == 0 )//有执行数据的时候，但不用生成质检单是提示
                    {
                        return "POSS当前收货单，无零件需质检！";
                    }
                    StringBuilder sql = new StringBuilder(1024);
                    sql.Append("SELECT * FROM dbo.wms_purchase(NOLOCK)  WHERE order_no='" + receving + "' AND enabled='Y' ");
                    List<WmsPurchase> _dt = dbConn.Query<WmsPurchase>(sql.ToString()).ToList();
                    if (_dt[0].OrderStatus == 40)
                    {
                        return "OKAuto" + QcOrder;// prove;
                    }

                    return "OK" + QcOrder;//prove;

                }
                else
                {
                    transaction.Rollback();
                    return "操作失败，请重新尝试！";
                }

                #endregion


            }
        }

        public List<WmsRejection> GetRejectionInfo()
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();

                string strSql = "select rejection_code,rejection_name from wms_rejection (nolock) where enabled = 'Y'";

                return dbConn.Query<WmsRejection>(strSql).ToList();

            }
        }
        public List<WmsPurchase> GetWmsPurchaseInfo(string order_no)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                dbConn.Open();
                StringBuilder sql = new StringBuilder(1024);
                sql.Append("select * from  wms_purchase (nolock)  where order_no = @orderNo");
                DynamicParameters parameters = new DynamicParameters();
                parameters.Add("@orderNo", order_no);

                return dbConn.Query<WmsPurchase>(sql.ToString(), parameters).ToList();

            }
        }
        public List<WmsPurchaseDetail> getItemNo(string orderNo, string partNo)
        {
            IDbConnection dbConn = dapperDbContext.GetDbConnection();
            StringBuilder sql = new StringBuilder(1024);
            sql.Append("select * from wms_purchase_detail (nolock) where order_no=@order_no and part_no=@partNo");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("@order_no", orderNo);
            parameters.Add("@partNo", partNo);
            List<WmsPurchaseDetail> getPurchaseDetail = dbConn.Query<WmsPurchaseDetail>(sql.ToString(), parameters).ToList();
            return getPurchaseDetail;
        }
        public List<SysPart> getPart(string partNo)
        {
            IDbConnection dbConn = dapperDbContext.GetDbConnection();
            StringBuilder sql = new StringBuilder(1024);
            sql.Append("select * from sys_part (nolock) where part_no=@partNo");
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("@partNo", partNo);
            List<SysPart> getParts = dbConn.Query<SysPart>(sql.ToString(), parameters).ToList();
            return getParts;
        }
        public string CheckStatus(string orderNo,string loginId)
        {

            IDbConnection dbConn = dapperDbContext.GetDbConnection();

			List<string> sqlStrings = new List<string>();
			List<DynamicParameters> parameterList = new List<DynamicParameters>();

			#region 修改收货主表
			//判断订单是否收货完成
			StringBuilder Ischeckpurchase = new StringBuilder(1024);
			DynamicParameters Ischeckpurchaseparameters = new DynamicParameters();
			//Ischeckpurchase.Append(@"select * from wms_purchase_detail  where order_no = @order_no and item_status=@item_status");
			Ischeckpurchase.Append(@"select * from wms_purchase_detail  where order_no = @order_no ");
			//Ischeckpurchaseparameters.Add("@item_status", (int)WmsEnumUtil.PurchaseOrderDetailStatus.COMPLETED);
			Ischeckpurchaseparameters.Add("@order_no", orderNo);

			List<WmsPurchaseDetail> CheckPurchaseList = dbConn.Query<WmsPurchaseDetail>(Ischeckpurchase.ToString(), Ischeckpurchaseparameters).ToList();
			var x = CheckPurchaseList.Sum(a => a.ItemStatus);

			if (CheckPurchaseList.Count * 40 == x)
			{
				//修改明细表
				//更新收货表
				StringBuilder COMPLETEDString = new StringBuilder(1024);
				COMPLETEDString.Append(@" update wms_purchase set order_status=@order_status,update_userid=@update_userid,update_time=@update_time where order_no = @order_no");
				DynamicParameters COMPLETEDStringparameters = new DynamicParameters();
				COMPLETEDStringparameters.Add("@order_no", orderNo);
				COMPLETEDStringparameters.Add("@order_status", (int)WmsEnumUtil.PurchaseOrderStatus.COMPLETED);
				COMPLETEDStringparameters.Add("@update_userid", loginId);
				COMPLETEDStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
				//dbConn.Execute(COMPLETEDString.ToString(), COMPLETEDStringparameters);
				sqlStrings.Add(COMPLETEDString.ToString());
				parameterList.Add(COMPLETEDStringparameters);
			}
            #endregion

            int t = SQLTransaction(sqlStrings, parameterList);

			////执行事务
			//IDbTransaction transaction = dbConn.BeginTransaction();

			//bool successCount = true;
			//for (int i = 0; i < sqlStrings.Count; i++)
			//{
			//	if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
			//	{
			//		successCount = false;
			//	}
			//}
            //return "OK";
            if (t>0)
            {
               // transaction.Commit();


                #region 判断订单是否收货完成
                //判断订单是否收货完成
                StringBuilder purchase = new StringBuilder(1024);
                purchase.Append(@"  select * from wms_purchase (nolock) where  order_no=@order_no ");
                DynamicParameters purchaseParameters = new DynamicParameters();
                purchaseParameters.Add("@order_no", orderNo);
                List<WmsPurchase> _CheckPurchaseList = dbConn.Query<WmsPurchase>(purchase.ToString(), purchaseParameters).ToList();

                if (_CheckPurchaseList[0].OrderStatus == (int)WmsEnumUtil.PurchaseOrderStatus.COMPLETED)
                {
                    return "OK";
                }
                else
                {
                    return "NO";
                }

                #endregion
            }
            else
            {
				return "NO";
			}


		}

		public string CheckPurchaseStatus(string receving, string loginId)
		{

			IDbConnection dbConn = dapperDbContext.GetDbConnection();


            List<string> sqlStrings = new List<string>();
            List<DynamicParameters> parameterList = new List<DynamicParameters>();

            #region 修改收货主表
            //判断订单是否收货完成
            StringBuilder Ischeckpurchase = new StringBuilder(1024);
            DynamicParameters Ischeckpurchaseparameters = new DynamicParameters();
            Ischeckpurchase.Append(@"select * from wms_purchase_detail  where order_no = @order_no and item_status=@item_status");
            Ischeckpurchaseparameters.Add("@item_status", (int)WmsEnumUtil.PurchaseOrderDetailStatus.COMPLETED);
            Ischeckpurchaseparameters.Add("@order_no", receving);

            List<WmsPurchaseDetail> CheckPurchaseList = dbConn.Query<WmsPurchaseDetail>(Ischeckpurchase.ToString(), Ischeckpurchaseparameters).ToList();
            var x = CheckPurchaseList.Sum(a => a.ItemStatus);

            if (CheckPurchaseList.Count * 40 == x)
            {
                //修改明细表
                //更新收货表
                StringBuilder COMPLETEDString = new StringBuilder(1024);
                COMPLETEDString.Append(@" update wms_purchase set order_status=@order_status,update_userid=@update_userid,update_time=@update_time where order_no = @order_no");
                DynamicParameters COMPLETEDStringparameters = new DynamicParameters();
                COMPLETEDStringparameters.Add("@order_no", receving);
                COMPLETEDStringparameters.Add("@order_status", (int)WmsEnumUtil.PurchaseOrderStatus.COMPLETED);
                COMPLETEDStringparameters.Add("@update_userid", loginId);
                COMPLETEDStringparameters.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                //dbConn.Execute(COMPLETEDString.ToString(), COMPLETEDStringparameters);
                sqlStrings.Add(COMPLETEDString.ToString());
                parameterList.Add(COMPLETEDStringparameters);
            }
            #endregion
            //执行事务
            IDbTransaction transaction = dbConn.BeginTransaction();

            bool successCount = true;
            for (int i = 0; i < sqlStrings.Count; i++)
            {
                if (dbConn.Execute(sqlStrings[i], parameterList[i], transaction) < 1)
                {
                    successCount = false;
                }
            }
            //return "OK";
            if (successCount)
            {
                transaction.Commit();
                return "OK" ;
            }
            else
            {
                transaction.Rollback();
                return "操作失败，请重新尝试！";
            }


		}

		public List<WmsPurchase> GetStandardList(string cartonno)
        {
            IDbConnection dbConn = dapperDbContext.GetDbConnection();

            StringBuilder getCustPartSQL = new StringBuilder(1024);
            if (cartonno == null || cartonno == "")
            {
                getCustPartSQL.Append(@"select * from wms_purchase (nolock) where order_status in (20,30) and enabled='Y' and order_type!=40 order by create_time desc ");
				//getCustPartSQL.Append(@"SELECT a.* FROM  wms_purchase a JOIN sys_stock b ON a.order_no=b.ref_order_no WHERE a.enabled='Y'AND b.enabled='Y' AND a.order_status IN(20,30) ORDER BY a.create_time desc");
			}
            else
            {
    //            getCustPartSQL.Append(@"select a.* from wms_purchase (nolock) as a left join wms_purchase_detail as b on a.order_no = b.order_no 
				//where a.order_status in (20,30) and a.enabled='Y' and order_type!=40  and a.order_no like '%" + cartonno + "%' order by a.create_time desc");
                getCustPartSQL.Append(@"select a.* from wms_purchase (nolock) as a  
				where a.order_status in (20,30) and a.enabled='Y' and order_type!=40  and a.order_no like '%" + cartonno + "%' order by a.create_time desc");

            }

			List<WmsPurchase> WmsPurchaseDetail = dbConn.Query<WmsPurchase>(getCustPartSQL.ToString()).ToList();

            return WmsPurchaseDetail;

        }


		/// <summary>
		///根据登录人id查询默认库位
		/// </summary>
		/// <param name="locateName"></param>
		/// <param name="loginId"></param>
		/// <returns></returns>
		public List<SysLocate> GetLogIdByLocateName(string loginId)
		{

			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();
                StringBuilder stringBuilder = new StringBuilder();
                //sql逻辑：根据登录人id来获取库位。目前逻辑不全
                stringBuilder.Append("SELECT top 1 a.locate_id,a.locate_name,a.locate_type,a.locate_capacity,b.enum_desc as locate_typeDesc,a.enabled FROM dbo.sys_locate a (nolock) "
                    + " LEFT JOIN sys_enum b (nolock) ON b.enum_type='sys_locate_type' and a.locate_type=b.enum_value "
                    + "  where a.locate_name='SH-001'");//先写死
                List<SysLocate> sysLocates = dbConn.Query<SysLocate>(stringBuilder.ToString()).ToList();


				return sysLocates;

			}

		}

		/// <summary>
		/// 根据库位获取库位信息
		/// </summary>
		/// <param name="locateName"></param>
		/// <param name="loginId"></param>
		/// <returns></returns>
		public List<SysLocate> GetLocateByName(string locateName, string loginId)
		{
			
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            { 
                dbConn.Open();

                StringBuilder stringBuilder = new StringBuilder();
                //sql逻辑：根据传来的条件查询库位是否存在。并且在 枚举表中判断库位类型
                if (locateName.Length == 0)
                {
					stringBuilder.Append("SELECT * FROM dbo.sys_locate (nolock) WHERE locate_type =50 ");//收货库位
				}
                else
                {
					stringBuilder.Append("SELECT a.*,b.enum_desc as locate_typeDesc,a.enabled FROM dbo.sys_locate a (nolock) "
					+ " LEFT JOIN sys_enum b (nolock) ON b.enum_type='sys_locate_type' and a.locate_type=b.enum_value "
					+ " WHERE a.locate_name = '" + locateName + "'");
				}
				

                List<SysLocate> sysLocates=dbConn.Query<SysLocate>(stringBuilder.ToString()).ToList();

                return sysLocates;
            }

		}
		/// <summary>
        /// 根据库位获取条码信息
        /// </summary>
        /// <param name="locateName"></param>
        /// <returns></returns>
		public List<SysStock> GetStockQtyByLocate(string locateName)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				StringBuilder stringBuilder = new StringBuilder();
				//sql逻辑：查询库存条码表， 判断当前库位的条码数量，条件为条码的状态为 50：已上架、60：已配料、80：NC隔离 标识为Y
				stringBuilder.Append("  SELECT SUM(qty) as qty FROM dbo.sys_stock (nolock) WHERE locate_name = '" + locateName + "' AND status IN ('50','60','80') and enabled='Y' ");
				List<SysStock> sysStocksLocateCount = dbConn.Query<SysStock>(stringBuilder.ToString()).ToList();//库位在库数
				return sysStocksLocateCount;
			}
		}

       /// <summary>
       /// 查询条码状态
       /// </summary>
       /// <param name="cartonNo"></param>
       /// <param name="orderNo"></param>
       /// <returns></returns>
        public List<SysStock_Extend> GetStockByCartonNo(string cartonNo,string orderNo)
        {
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{

                StringBuilder sql=new StringBuilder(1024);
                if (orderNo.Length>0)
                {
					//  sql.Append("select * from sys_stock (nolock) where ref_order_no='" + orderNo + "' ");
					sql.Append("select a.* ,b.instock_type AS IsDirectWarehousing from sys_stock (nolock) a LEFT JOIN dbo.sys_part b ON a.part_id=b.part_id where a.ref_order_no='" + orderNo + "' ");
				}
                else
                {
					//sql.Append("select * from sys_stock (nolock) where ref_order_no in ( select ref_order_no from sys_stock (nolock) where carton_no='"+ cartonNo + "') ");
					sql.Append("select a.* ,b.instock_type AS IsDirectWarehousing from sys_stock (nolock) a LEFT JOIN dbo.sys_part b ON a.part_id=b.part_id  where a.ref_order_no in ( select ref_order_no from sys_stock (nolock) where carton_no='" + cartonNo + "') ");

				}
                List<SysStock_Extend> sysStocks = dbConn.Query<SysStock_Extend>(sql.ToString()).ToList();
                return sysStocks;

			}

		}

		/// <summary>
		/// 委外收货，新增 wms_subcontract_data
		/// </summary>
		/// <param name="orderNo"></param>
		/// <returns></returns>
		public List<WmsPurchase> GetWmsPurchaseByOrderNo(string orderNo)
        {
            using (IDbConnection dbConn =dapperDbContext.GetDbConnection())
            {
				StringBuilder sqlSubcontract = new StringBuilder(1024);
				sqlSubcontract.Append("select * from [dbo].[wms_purchase] where order_no='"+ orderNo + "' ");

				List<WmsPurchase> dtSubcontract = dbConn.Query<WmsPurchase>(sqlSubcontract.ToString()).ToList();
                return dtSubcontract;
			}
		}

        /// <summary>
        /// 根据零件号id,查零件号信息
        /// </summary>
        /// <param name="partId"></param>
        /// <returns></returns>
        public SysPart_Extend GetPartExtendByPartId(string partId)
        {
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				StringBuilder sqlSubcontract = new StringBuilder(1024);
				sqlSubcontract.Append("SELECT * FROM dbo.sys_part(NOLOCK) WHERE part_id='"+ partId + "'  AND enabled='Y' ");

				SysPart_Extend dtSubcontract = dbConn.Query<SysPart_Extend>(sqlSubcontract.ToString()).First();
				return dtSubcontract;
			}
		}


		/// <summary>
		/// 事务批量执行添加、修改
		/// </summary>
		/// <param name="sqlStrings"></param>
		/// <param name="parameterList"></param>
		/// <returns></returns>
		public int SQLTransaction(List<string> sqlStrings, List<DynamicParameters> parameterList)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				if (dbConn.State == ConnectionState.Closed)
				{
					dbConn.Open();
				}
				//执行事务
				IDbTransaction transaction = dbConn.BeginTransaction();
				if (parameterList == null || parameterList.Count == 0)
				{
					try
					{
						for (int i = 0; i < sqlStrings.Count; i++)
						{
							dbConn.Execute(sqlStrings[i], null, transaction);
						}
						transaction.Commit();
						return 1;
					}
					catch (Exception exception)
					{
						transaction.Rollback();
						return 0;
					}
				}
				else
				{
					try
					{
						for (int i = 0; i < sqlStrings.Count; i++)
						{
							dbConn.Execute(sqlStrings[i], parameterList[i], transaction);
						}
						transaction.Commit();
						return 1;
					}
					catch (Exception exception)
					{
						transaction.Rollback();
						return 0;
					}
				}
			}
		}

        public List<WmsPurchaseDetail_Extend> GetWmsPurchaseDetailByRecqty(string orderNo,string cartonNo)
        {
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				List<string> sqlStrings = new List<string>();
				List<DynamicParameters> parameterList = new List<DynamicParameters>();


				StringBuilder sql = new StringBuilder(1024);
				sql.Append("  SELECT SUM(a.qty)AS qty, SUM(a.rec_qty) AS recqty FROM wms_purchase_detail a RIGHT JOIN sys_stock b ON a.part_id=b.part_id AND a.order_no=b.ref_order_no"
							+ "  WHERE a.enabled = 'Y' AND b.enabled = 'Y' AND b.ref_order_no = '" + orderNo + "' AND b.carton_no = '" + cartonNo + "'  GROUP BY  b.ref_order_no, b.carton_no, b.part_id");
				List<WmsPurchaseDetail_Extend> wmsPurchaseDetails = dbConn.Query<WmsPurchaseDetail_Extend>(sql.ToString()).ToList();
                if (wmsPurchaseDetails.Count() > 0)
                {
                    return wmsPurchaseDetails;

				}
                return null;
                
			}

		}





		public string Up_StockQty(string cartonNo, string groupNo, string loginId, string orderNo, string qtyReceived,string locateName)
        {
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				List<string> sqlStrings = new List<string>();
				List<DynamicParameters> parameterList=new List<DynamicParameters>();

				//StringBuilder _sql = new StringBuilder(1024);
				//_sql.Append(" SELECT QTY  FROM  dbo.sys_stock  WHERE carton_no='"+ cartonNo + "' AND  ref_order_no='"+ orderNo + "' AND enabled='Y'  ");
				//List<WmsPurchaseDetail_Extend> _wmsPurchaseDetails = dbConn.Query<WmsPurchaseDetail_Extend>(_sql.ToString()).ToList();

				//            decimal cartonNoQSnpQty = decimal.Parse(qtyReceived)-_wmsPurchaseDetails[0].Qty ;



				//StringBuilder sql = new StringBuilder(1024);
				//sql.Append("  SELECT SUM(a.qty)AS qty, SUM(a.rec_qty) AS recqty FROM wms_purchase_detail a RIGHT JOIN sys_stock b ON a.part_id=b.part_id AND a.order_no=b.ref_order_no"
				//			+ "  WHERE a.enabled = 'Y' AND b.enabled = 'Y' AND b.ref_order_no = '"+ orderNo + "' AND b.carton_no = '"+ cartonNo + "'  GROUP BY  b.ref_order_no, b.carton_no, b.part_id");
				//List<WmsPurchaseDetail_Extend> wmsPurchaseDetails= dbConn.Query<WmsPurchaseDetail_Extend>(sql.ToString()).ToList();
				////判断 应收数量<实收数量+修改的数量
				//if (wmsPurchaseDetails[0].Qty < wmsPurchaseDetails[0].RecQty + cartonNoQSnpQty)
				//            {
				//	return "箱条码：[" + cartonNo + "]的数量不可更改！";
				//}

				List<SysStock_Extend> sysStocks = GetStockByCartonNo(cartonNo, orderNo);
				List<SysStock_Extend> _sysStocks = sysStocks.Where(a => a.CartonNo == cartonNo && a.Status==25).ToList();//条码状态为已收货
				List<SysLocate> sysLocates = GetLocateByName(locateName, loginId);
				//修改条码数量
				StringBuilder sql2 = new StringBuilder(1024);
				if (orderNo.Length > 0)
				{
					sql2.Append("UPDATE dbo.sys_stock SET qty=@qty,update_userid=@update_userid , update_time=@update_time  WHERE carton_no=@carton_no AND  ref_order_no=@ref_order_no AND enabled='Y'");
					
					DynamicParameters updateStringparameters3 = new DynamicParameters();
					updateStringparameters3.Add("@qty", qtyReceived);
					updateStringparameters3.Add("@update_userid", loginId);
					updateStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
					updateStringparameters3.Add("@carton_no", cartonNo);
					updateStringparameters3.Add("@ref_order_no", orderNo);
					sqlStrings.Add(sql2.ToString());
					parameterList.Add(updateStringparameters3);

				}


				//更改条码表状态
				string IsDirectWarehousing = (_sysStocks[0].IsDirectWarehousing == null || _sysStocks[0].IsDirectWarehousing == "0") ? "0" : "1";//是否直入库

				#region 新增 sys_stock_trans 事务表

				//新增 sys_stock_trans 事务表
				StringBuilder updateString4 = new StringBuilder(1024);
				updateString4.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,
                                        @unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,
                                        @dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled 
                                        ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");

				DynamicParameters updateStringparameters4 = new DynamicParameters();
				if (IsDirectWarehousing != "1")//判断--箱条码的信息是否是直入库 ，不是直入库 
				{
					updateStringparameters4.Add("@trans_code", (int)WmsEnumUtil.TransType.RC);
				}
				else
				{
					//直入库
					updateStringparameters4.Add("@trans_code", (int)WmsEnumUtil.TransType.INSTOCK);
				}
				//updateStringparameters4.Add("@trans_code", (int)WmsEnumUtil.TransType.QC);
				updateStringparameters4.Add("@carton_no", _sysStocks[0].CartonNo);
				updateStringparameters4.Add("@part_id", _sysStocks[0].PartId);
				updateStringparameters4.Add("@part_no", _sysStocks[0].PartNo);
				updateStringparameters4.Add("@part_spec", _sysStocks[0].PartSpec);
				updateStringparameters4.Add("@src_locate_id", 0);
				updateStringparameters4.Add("@src_locate_name", null);
				updateStringparameters4.Add("@dest_locate_id", sysLocates[0].LocateId);
				updateStringparameters4.Add("@dest_locate_name", locateName);
				updateStringparameters4.Add("@old_qty", qtyReceived);
				updateStringparameters4.Add("@new_qty", qtyReceived);
				updateStringparameters4.Add("@trans_qty", qtyReceived);
				updateStringparameters4.Add("@old_status", 20);
				if (IsDirectWarehousing != "1")//判断--箱条码的信息是否是直入库 ，不是直入库 
				{
					updateStringparameters4.Add("@new_status", 25);
				}
				else
				{
					//直入库
					updateStringparameters4.Add("@new_status", 50);
				}

				updateStringparameters4.Add("@old_qms_status", "N");
				updateStringparameters4.Add("@new_qms_status", "N");
				updateStringparameters4.Add("@unit", _sysStocks[0].Unit);
				updateStringparameters4.Add("@factory_id", _sysStocks[0].FactoryId);
				updateStringparameters4.Add("@factory_code", _sysStocks[0].FactoryCode);
				updateStringparameters4.Add("@src_erp_warehouse", _sysStocks[0].ErpWarehouse);
				updateStringparameters4.Add("@dest_erp_warehouse", _sysStocks[0].ErpWarehouse);
				updateStringparameters4.Add("@src_warehouse_id", 0);
				updateStringparameters4.Add("@src_warehouse_name", "");
				updateStringparameters4.Add("@dest_warehouse_id", sysLocates[0].WarehouseId);
				updateStringparameters4.Add("@dest_warehouse_name", sysLocates[0].WarehouseName);
				updateStringparameters4.Add("@src_zone_id", 0);
				updateStringparameters4.Add("@src_zone_name", "");
				updateStringparameters4.Add("@dest_zone_id", sysLocates[0].ZoneId);
				updateStringparameters4.Add("@dest_zone_name", sysLocates[0].ZoneName);
				updateStringparameters4.Add("@enabled", _sysStocks[0].Enabled);
				updateStringparameters4.Add("@update_userid", loginId);
				updateStringparameters4.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
				updateStringparameters4.Add("@create_userid", loginId);
				updateStringparameters4.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
				updateStringparameters4.Add("@guid", Guid.NewGuid());

				sqlStrings.Add(updateString4.ToString());
				parameterList.Add(updateStringparameters4);


				#endregion

				

				int i = SQLTransaction(sqlStrings, parameterList);

                if (i > 0)
                {
                    return "OK" + "箱条码：["+ cartonNo + "]实际库存数量修改成功！";

                }
                else
                {
                    return "箱条码：[" + cartonNo + "]实际库存数量修改失败！";
                }
                
			}
		}

        /// <summary>
        /// 修改数量，支给件(后绑定)
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <param name="groupNo"></param>
        /// <param name="loginId"></param>
        /// <param name="orderNo"></param>
        /// <param name="qtyReceived"></param>
        /// <param name="locateName"></param>
        /// <returns></returns>
        public string Up_StockQtyPostBinding(string cartonNo, string groupNo, string loginId, string orderNo, string qtyReceived, string locateName)
        {
            using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
            {
                List<string> sqlStrings = new List<string>();
                List<DynamicParameters> parameterList = new List<DynamicParameters>();

                List<SysStock_Extend> sysStocks = GetStockByCartonNo(cartonNo, orderNo);//根据箱条码和单号找到stock表数据
                List<SysStock_Extend> _sysStocks = sysStocks.Where(a => a.CartonNo == cartonNo && (a.Status !=20|| a.Status!=150)).ToList();//条码状态为已收货

                List<SysLocate> sysLocates = GetLocateByName(locateName, loginId);


                #region 采购明细表修改应收数量

                //判断明细表中此箱条码的零件号是否存在

                StringBuilder getPurchaseDetailSQL = new StringBuilder(1024);
                getPurchaseDetailSQL.Append("SELECT * FROM wms_purchase_detail (nolock) WHERE order_no= @order_no ");
                DynamicParameters wmsPurchaseDetailParameters = new DynamicParameters();
                wmsPurchaseDetailParameters.Add("@order_no", orderNo);
                List<WmsPurchaseDetail> ifPurchaseDetail = dbConn.Query<WmsPurchaseDetail>(getPurchaseDetailSQL.ToString(), wmsPurchaseDetailParameters).ToList();//找到采购明细数据

                List<WmsPurchaseDetail> ifPurchaseDetailByPart = ifPurchaseDetail.Where(a => a.PartNo == _sysStocks[0].PartNo && a.Enabled == "Y").ToList();//找出当前扫描箱条码零件号的采购明细
                decimal _recqty = 0;
                if (ifPurchaseDetailByPart.Count > 0)//判断修改的数量是否大于采购明细中应收的数量
                {
                    SysPart_Extend sysPart = GetPartExtendByPartId(ifPurchaseDetailByPart[0].PartId.ToString());
                    if (sysPart != null)
                    {
                         _recqty = (ifPurchaseDetailByPart[0].RecQty- _sysStocks[0].Qty)+ decimal.Parse(qtyReceived);// 预计实收数量（实收数量+当前条码的数量）用于判断原由的实收数量+当前扫描的条码数量是否大于应收数量
                        decimal revupperQty = 0;//收货上限比
                        decimal revdowmperQty = 0;//收货下限比

                        bool Issql = true;
                        if (sysPart.revdowmper > 0 && sysPart.revdowmper != null && sysPart.revupper > 0 && sysPart.revupper != null)
                        {
                            revupperQty = ifPurchaseDetailByPart[0].Qty * (1 + sysPart.revupper);//最多收多少
                            revdowmperQty = ifPurchaseDetailByPart[0].Qty * (1 - sysPart.revdowmper);//最少收多少
                            if (_recqty <= revupperQty)   //预计实收数量<=收货上限数量
                            {
                                Issql = false;
                            }

                        }
                        else if (sysPart.revupper > 0 && sysPart.revupper != null)//收货上限比。实收数量可以大于应收数量
                        {
                            revupperQty = ifPurchaseDetailByPart[0].Qty * (1 + sysPart.revupper);
                            if (_recqty <= revupperQty)//预计实收数量<=收货上限数量
                            {
                                Issql = false;
                            }

                        }
                        else if (sysPart.revdowmper > 0 && sysPart.revdowmper != null) //收货下限比。应收数量可以小于实收数量
                        {
                            revdowmperQty = ifPurchaseDetailByPart[0].Qty * (1 - sysPart.revdowmper);
                            if (_recqty <= ifPurchaseDetailByPart[0].Qty)// 预计实收数量  <= 应收数量
                            {
                                Issql = false;
                            }

                        }
                        else //预计实收数量  <= 应收数量
                        {
                            if (_recqty <= ifPurchaseDetailByPart[0].Qty)//预计实收数量  <= 应收数量
                            {
                                Issql = false;
                            }
                        }
                        if (Issql)
                        {
                            // 提示 " [M0090105] : 箱里的零件数量大于了应收数量!";
                            return "箱里的零件数量大于了应收数量!";
                          
                        }


                    }


                    #region 修改采购明细表
                    StringBuilder updateString2 = new StringBuilder(1024);
                    //本来修改的应收数量，现在改为实收数量
                    updateString2.Append(@" update wms_purchase_detail set rec_qty= @rec_qty ,update_userid = @update_userid ,update_time =@update_time where  guid =@guid");

                    DynamicParameters updateStringparameters2 = new DynamicParameters();
                    updateStringparameters2.Add("@rec_qty", _recqty);
                    updateStringparameters2.Add("@update_userid", loginId);
                    updateStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    updateStringparameters2.Add("@guid", ifPurchaseDetailByPart[0].Guid);
                    sqlStrings.Add(updateString2.ToString());
                    parameterList.Add(updateStringparameters2);
                    #endregion

                }
                else
                {
                    // 提示 " 扫描的箱条码中的零件号你不在采购明细中，请重新扫描！";
                    return "扫描的箱条码中的零件号你不在采购明细中，请重新扫描！";
                
                }
                #endregion


                //修改条码数量
                StringBuilder sql2 = new StringBuilder(1024);
                if (orderNo.Length > 0)
                {
                    sql2.Append("UPDATE dbo.sys_stock SET qty=@qty,update_userid=@update_userid , update_time=@update_time  WHERE carton_no=@carton_no AND  ref_order_no=@ref_order_no AND enabled='Y'");

                    DynamicParameters updateStringparameters3 = new DynamicParameters();
                    updateStringparameters3.Add("@qty", qtyReceived);
                    updateStringparameters3.Add("@update_userid", loginId);
                    updateStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    updateStringparameters3.Add("@carton_no", cartonNo);
                    updateStringparameters3.Add("@ref_order_no", orderNo);
                    sqlStrings.Add(sql2.ToString());
                    parameterList.Add(updateStringparameters3);

                }


                //更改条码表状态
                string IsDirectWarehousing = (_sysStocks[0].IsDirectWarehousing == null || _sysStocks[0].IsDirectWarehousing == "0") ? "0" : "1";//是否直入库

                #region 新增 sys_stock_trans 事务表

                //新增 sys_stock_trans 事务表
                StringBuilder updateString4 = new StringBuilder(1024);
                updateString4.Append(@" INSERT INTO[dbo].[sys_stock_trans]
                                                    ([trans_code]
                                                    ,[carton_no]
                                                    ,[part_id]
                                                    ,[part_no]
                                                    ,[part_spec]
                                                    ,[src_locate_id]
                                                    ,[src_locate_name]
                                                    ,[dest_locate_id]
                                                    ,[dest_locate_name]
                                                    ,[old_qty]
                                                    ,[new_qty]
                                                    ,[trans_qty]
                                                    ,[old_status]
                                                    ,[new_status]
                                                    ,[old_qms_status]
                                                    ,[new_qms_status]
                                                    ,[unit]
                                                    ,[factory_id]
                                                    ,[factory_code]
                                                    ,[src_erp_warehouse]
                                                    ,[dest_erp_warehouse]
                                                    ,[src_warehouse_id]
                                                    ,[src_warehouse_name]
                                                    ,[dest_warehouse_id]
                                                    ,[dest_warehouse_name]
                                                    ,[src_zone_id]
                                                    ,[src_zone_name]
                                                    ,[dest_zone_id]
                                                    ,[dest_zone_name]
                                                    ,[enabled]
                                                    ,[update_userid]
                                                    ,[update_time]
                                                    ,[create_userid]
                                                    ,[create_time]
                                                    ,[guid])
                                                  VALUES (@trans_code,@carton_no,@part_id,@part_no,@part_spec,@src_locate_id ,@src_locate_name ,@dest_locate_id ,@dest_locate_name ,@old_qty 
                                        ,@new_qty ,@trans_qty ,@old_status ,@new_status ,@old_qms_status ,@new_qms_status ,
                                        @unit ,@factory_id ,@factory_code ,@src_erp_warehouse ,@dest_erp_warehouse ,@src_warehouse_id ,@src_warehouse_name ,
                                        @dest_warehouse_id ,@dest_warehouse_name ,@src_zone_id ,@src_zone_name ,@dest_zone_id ,@dest_zone_name ,@enabled 
                                        ,@update_userid ,@update_time ,@create_userid ,@create_time ,@guid )");

                DynamicParameters updateStringparameters4 = new DynamicParameters();
                if (IsDirectWarehousing != "1")//判断--箱条码的信息是否是直入库 ，不是直入库 
                {
                    updateStringparameters4.Add("@trans_code", (int)WmsEnumUtil.TransType.RC);
                }
                else
                {
                    //直入库
                    updateStringparameters4.Add("@trans_code", (int)WmsEnumUtil.TransType.INSTOCK);
                }
                //updateStringparameters4.Add("@trans_code", (int)WmsEnumUtil.TransType.QC);
                updateStringparameters4.Add("@carton_no", _sysStocks[0].CartonNo);
                updateStringparameters4.Add("@part_id", _sysStocks[0].PartId);
                updateStringparameters4.Add("@part_no", _sysStocks[0].PartNo);
                updateStringparameters4.Add("@part_spec", _sysStocks[0].PartSpec);
                updateStringparameters4.Add("@src_locate_id", 0);
                updateStringparameters4.Add("@src_locate_name", null);
                updateStringparameters4.Add("@dest_locate_id", sysLocates[0].LocateId);
                updateStringparameters4.Add("@dest_locate_name", locateName);
                updateStringparameters4.Add("@old_qty", qtyReceived);
                updateStringparameters4.Add("@new_qty", qtyReceived);
                updateStringparameters4.Add("@trans_qty", qtyReceived);
                updateStringparameters4.Add("@old_status", 20);
                if (IsDirectWarehousing != "1")//判断--箱条码的信息是否是直入库 ，不是直入库 
                {
                    updateStringparameters4.Add("@new_status", 25);
                }
                else
                {
                    //直入库
                    updateStringparameters4.Add("@new_status", 50);
                }

                updateStringparameters4.Add("@old_qms_status", "N");
                updateStringparameters4.Add("@new_qms_status", "N");
                updateStringparameters4.Add("@unit", _sysStocks[0].Unit);
                updateStringparameters4.Add("@factory_id", _sysStocks[0].FactoryId);
                updateStringparameters4.Add("@factory_code", _sysStocks[0].FactoryCode);
                updateStringparameters4.Add("@src_erp_warehouse", _sysStocks[0].ErpWarehouse);
                updateStringparameters4.Add("@dest_erp_warehouse", _sysStocks[0].ErpWarehouse);
                updateStringparameters4.Add("@src_warehouse_id", 0);
                updateStringparameters4.Add("@src_warehouse_name", "");
                updateStringparameters4.Add("@dest_warehouse_id", sysLocates[0].WarehouseId);
                updateStringparameters4.Add("@dest_warehouse_name", sysLocates[0].WarehouseName);
                updateStringparameters4.Add("@src_zone_id", 0);
                updateStringparameters4.Add("@src_zone_name", "");
                updateStringparameters4.Add("@dest_zone_id", sysLocates[0].ZoneId);
                updateStringparameters4.Add("@dest_zone_name", sysLocates[0].ZoneName);
                updateStringparameters4.Add("@enabled", _sysStocks[0].Enabled);
                updateStringparameters4.Add("@update_userid", loginId);
                updateStringparameters4.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                updateStringparameters4.Add("@create_userid", loginId);
                updateStringparameters4.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                updateStringparameters4.Add("@guid", Guid.NewGuid());

                sqlStrings.Add(updateString4.ToString());
                parameterList.Add(updateStringparameters4);


                #endregion



                int i = SQLTransaction(sqlStrings, parameterList);

                if (i > 0)
                {
                    return "OK" + "箱条码：[" + cartonNo + "]实际库存数量修改成功！";

                }
                else
                {
                    return "箱条码：[" + cartonNo + "]实际库存数量修改失败！";
                }

            }
        }



        /// <summary>
        /// 通过箱条码获取收货订单的明细信息  , 支给件没有信息就新增信息（后绑定新增方法）
        /// </summary>
        /// <param name="cartonNo"></param>
        /// <param name="receving"></param>
        /// <returns></returns>
        public SetObjectDetail GetCartonSummaryInfoNew(string cartonNo, string receving, string supportingParts, string loginId, string locateName)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				SetObjectDetail setDetail = new SetObjectDetail();
				string zgj_order = string.Empty;//采购订单号

				if (supportingParts == "Y") 
                {
					#region 支给件逻辑
					//亿日二维码规则
					//工厂代码，零件号，箱条码，数量，单位，供应商代码,生产批次
					//测试：1010|A06-6801630-V03|ZPO20230227001|100||220310|ZTL-001
					//cartonNo=
					string[] cartonNoList = cartonNo.Split('|');

                    string plant_no = string.Empty;//工厂代码
                    string part_no = string.Empty; //零件号
                    string carton_no = string.Empty; //箱条码
					string num = string.Empty;//数量   1
                    string unit = string.Empty;//单位
					string zgj_vendor = string.Empty;//供应商代码
					string zgj_lotno = string.Empty;//确认一下 批次号

                    if (cartonNoList.Length == 7)// 拆分二维码

					{
                        plant_no = cartonNoList[0].ToString();
						part_no = cartonNoList[1].ToString();
                        carton_no = cartonNo;//cartonNoList[2].ToString();
						num = cartonNoList[3].ToString();
						unit = cartonNoList[4].ToString();
						zgj_vendor = cartonNoList[5].ToString();
						zgj_lotno = cartonNoList[6].ToString();


					}
					else
					{
						setDetail.type = "NO";
						setDetail.message = "二维码解析失败，请确认！";
						setDetail.wmsObjectDetail = null;
						return setDetail;
					}
                    
                    

					//if (receving != "" && receving != zgj_order)
					//{
					//	setDetail.type = "NO";
					//	setDetail.message = "该条码不在此订单内！";
					//	setDetail.wmsObjectDetail = null;
					//	return setDetail;
					//}

					//验证条件
					#region 验证工厂

					//验证扫描的二维码里的工厂，在工厂表中是否存在
					StringBuilder getPlantSQL = new StringBuilder(1024);
					getPlantSQL.Append("    SELECT * FROM dbo.sys_factory  (nolock)  WHERE enabled='Y' AND factor_id=@factor_id");
					DynamicParameters getPlantparameters = new DynamicParameters();
					getPlantparameters.Add("@factor_id", plant_no);
					List<SysFactory> SysFactory = dbConn.Query<SysFactory>(getPlantSQL.ToString(), getPlantparameters).ToList();
					if (SysFactory == null || SysFactory.Count == 0)
					{
						setDetail.type = "NO";
						setDetail.message = "[" + plant_no + "]:工厂不存在，无效二维码，请确认！";
						setDetail.wmsObjectDetail = null;
						return setDetail;
					}


					#endregion

					#region 验证零件号

					//验证扫描的二维码里的零件号，在零件表中是否存在
					StringBuilder getPartSQL = new StringBuilder(1024);
					getPartSQL.Append("   SELECT * FROM dbo.sys_part (nolock)  WHERE enabled='Y' AND part_no=@part_no ");
					DynamicParameters getPartparameters = new DynamicParameters();
					getPartparameters.Add("@part_no", part_no);
					List<SysPart> SysPart = dbConn.Query<SysPart>(getPartSQL.ToString(), getPartparameters).ToList();
					if (SysPart == null || SysPart.Count == 0)
					{
						setDetail.type = "NO";
						setDetail.message = "[" + part_no + "]:零件号不存在，为无效二维码，请确认！";
						setDetail.wmsObjectDetail = null;
						return setDetail;
					}

					#endregion

					#region 验证箱条码

					//判断箱条码是否已存在
					StringBuilder ifcartonNoSql = new StringBuilder(1024);
					ifcartonNoSql.Append("select * from sys_stock (nolock) where carton_no = @carton_no and enabled='Y'  ");
					DynamicParameters ifcartonNoparameters = new DynamicParameters();
					ifcartonNoparameters.Add("@carton_no", carton_no);
					List<SysStock> getcartonNo = dbConn.Query<SysStock>(ifcartonNoSql.ToString(), ifcartonNoparameters).ToList();
					if (getcartonNo.Count > 0)
					{
                        if (getcartonNo[0].Status == 25)//条码为已收货
                        {
							setDetail.type = "NUM";
							setDetail.message = "请输入数量!";
							setDetail.wmsObjectDetail = null;
							return setDetail;
						}
                        else
                        {
							setDetail.type = "NO";
							setDetail.message = "箱条码已扫描，请确认！";
							setDetail.wmsObjectDetail = null;
							return setDetail;
						}
						
					}

					#endregion

					//SQL 执行集合
					List<string> insertStrings = new List<string>();
					List<DynamicParameters> insertparameterList = new List<DynamicParameters>();

					//获取供应商信息
					#region 获取供应商信息


					StringBuilder getCustPartSQL2 = new StringBuilder(1024);
					getCustPartSQL2.Append("   select * from sys_vendor (nolock) where vendor_code=@vendor_code ");
					DynamicParameters getCustPartparameters2 = new DynamicParameters();
					getCustPartparameters2.Add("@vendor_code", zgj_vendor);
					List<SysVendor> vendors = dbConn.Query<SysVendor>(getCustPartSQL2.ToString(), getCustPartparameters2).ToList();

					string vendor_id = "";
					string vendor_code = "";
					string vendor_name = "";
                    string dock = "";
					if (vendors != null && vendors.Count > 0)
					{
						vendor_id = vendors[0].VendorId.ToString();
						vendor_code = vendors[0].VendorCode.ToString();
						vendor_name = vendors[0].VendorName.ToString();
					}
					else
					{
                        //vendor_code = zgj_vendor;
                        //vendor_name = zgj_vendor;
                        setDetail.type = "NO";
                        setDetail.message = "[" + zgj_vendor + "]:供应商代码不存在，请确认！";
                        setDetail.wmsObjectDetail = null;
                        return setDetail;
                    }

                    #endregion

					#region 库位表信息

					//StringBuilder getCustPartSQL3 = new StringBuilder(1024);
					//getCustPartSQL3.Append("select * from sys_locate (nolock) where locate_type =@locate_type  ");
					//DynamicParameters getCustPartparameters3 = new DynamicParameters();
					//getCustPartparameters3.Add("@locate_type", (int)WmsEnumUtil.LocateType.COLLECT_LOCATE);
					//List<SysLocate> syslocates = dbConn.Query<SysLocate>(getCustPartSQL3.ToString(), getCustPartparameters3).ToList();

					StringBuilder getLocateSQL = new StringBuilder(1024);
					DynamicParameters getLocateparameters = new DynamicParameters();
					if (locateName.Length > 0)
					{
						getLocateSQL.Append(" select * from sys_locate (nolock) where  locate_name=@locate_name  ");
						getLocateparameters.Add("@locate_name", locateName);
					}
					else
					{
						getLocateSQL.Append(" select * from sys_locate (nolock) where locate_type =@locate_type  ");
						getLocateparameters.Add("@locate_type", (int)WmsEnumUtil.LocateType.COLLECT_LOCATE);
					}

					List<SysLocate> syslocates = dbConn.Query<SysLocate>(getLocateSQL.ToString(), getLocateparameters).ToList();
					if (syslocates == null || syslocates.Count == 0)
					{
						setDetail.message = "收货库位不存在，请确认！";
						setDetail.wmsObjectDetail = null;
						return setDetail;
					}


					#endregion


					#region 新增库存条码表

					StringBuilder insertString3 = new StringBuilder(1024);
					insertString3.Append(@" INSERT INTO [dbo].[sys_stock]
                                             ([vendor_id]
                                             ,[vendor_code]
                                             ,[carton_no]
                                             ,[part_id]
                                             ,[part_no]
                                             ,[part_spec]
                                             ,[lot_no]
                                             ,[fix_lot_no]
                                             ,[status]
                                             ,[qty]
                                             ,[snp_qty]
                                             ,[locate_id]
                                             ,[locate_name]
                                             ,[group_no]
                                             ,[erp_warehouse]
                                             ,[date_code]
                                             ,[qms_status]
                                             ,[ref_order_no]
                                             ,[unit]
                                             ,[dock]
                                             ,[warehouse_id]
                                             ,[warehouse_name]
                                             ,[zone_id]
                                             ,[zone_name]
                                             ,[printed]
                                             ,[print_time]
                                             ,[remark]
                                             ,[factory_id]
                                             ,[factory_code]
                                             ,[enabled]
                                             ,[create_userid]
                                             ,[create_time]
                                             ,[update_userid]
                                             ,[update_time]
                                             ,[guid]
                                             )
                                              VALUES ( @vendor_id ,@vendor_code ,@carton_no ,@part_id ,@part_no ,@part_spec ,@lot_no ,@fix_lot_no ,@status ,@qty ,@snp_qty ,@locate_id ,@locate_name ,@group_no ,@erp_warehouse ,@date_code ,@qms_status ,@ref_order_no ,@unit ,@dock ,@warehouse_id ,@warehouse_name ,@zone_id ,@zone_name ,@printed ,@print_time ,@remark ,@factory_id ,@factory_code ,@enabled ,@create_userid ,@create_time ,@update_userid ,@update_time ,@guid )");

					DynamicParameters insertStringparameters3 = new DynamicParameters();
					insertStringparameters3.Add("@vendor_id ", vendor_id);
					insertStringparameters3.Add("@vendor_code ", vendor_name);
					insertStringparameters3.Add("@carton_no ", carton_no);
					insertStringparameters3.Add("@part_id ", SysPart[0].PartId);
					insertStringparameters3.Add("@part_no ", SysPart[0].PartNo);
					insertStringparameters3.Add("@part_spec ", SysPart[0].PartSpec);
					insertStringparameters3.Add("@lot_no ", zgj_lotno);
					insertStringparameters3.Add("@fix_lot_no ", "");
					insertStringparameters3.Add("@status ", 20);
					insertStringparameters3.Add("@qty ",num );
					insertStringparameters3.Add("@snp_qty ", num);
					insertStringparameters3.Add("@locate_id ", syslocates[0].LocateId);
					insertStringparameters3.Add("@locate_name ", syslocates[0].LocateName);
					insertStringparameters3.Add("@group_no ", "");
					insertStringparameters3.Add("@erp_warehouse ", "");
					insertStringparameters3.Add("@date_code ", "");
					insertStringparameters3.Add("@qms_status ", "");
					insertStringparameters3.Add("@ref_order_no ", receving);
					insertStringparameters3.Add("@unit ", unit);
                    insertStringparameters3.Add("@dock ", dock);
                    insertStringparameters3.Add("@warehouse_id ", "'"+ syslocates[0].WarehouseId + "'");
					insertStringparameters3.Add("@warehouse_name ", "'" + syslocates[0].WarehouseName + "'");
					insertStringparameters3.Add("@zone_id ", "'" + syslocates[0].ZoneId + "'");
					insertStringparameters3.Add("@zone_name ", "'" + syslocates[0].ZoneName + "'");
					insertStringparameters3.Add("@printed ", "");
					insertStringparameters3.Add("@print_time ", "");
					insertStringparameters3.Add("@remark ", "");
					insertStringparameters3.Add("@factory_id ", SysFactory[0].FactoryId);
					insertStringparameters3.Add("@factory_code ", SysFactory[0].FactoryCode);
					insertStringparameters3.Add("@enabled", "Y");
					insertStringparameters3.Add("@update_userid", loginId);
					insertStringparameters3.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
					insertStringparameters3.Add("@create_userid", loginId);
					insertStringparameters3.Add("@create_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
					insertStringparameters3.Add("@guid", Guid.NewGuid());

					insertStrings.Add(insertString3.ToString());
					insertparameterList.Add(insertStringparameters3);
                    #endregion

                    #region 采购明细表修改应收数量  注释


                    //判断明细表中此箱条码的零件号是否存在

                    StringBuilder getPurchaseDetailSQL = new StringBuilder(1024);
                    getPurchaseDetailSQL.Append("SELECT * FROM wms_purchase_detail (nolock) WHERE order_no= @order_no ");
                    DynamicParameters wmsPurchaseDetailParameters = new DynamicParameters();
                    wmsPurchaseDetailParameters.Add("@order_no", receving);
                    List<WmsPurchaseDetail> ifPurchaseDetail = dbConn.Query<WmsPurchaseDetail>(getPurchaseDetailSQL.ToString(), wmsPurchaseDetailParameters).ToList();

                    List<WmsPurchaseDetail> ifPurchaseDetailByPart = ifPurchaseDetail.Where(a => a.PartNo == part_no && a.Enabled == "Y").ToList();

                    if (ifPurchaseDetailByPart.Count > 0)
                    {
                        SysPart_Extend sysPart = GetPartExtendByPartId(ifPurchaseDetailByPart[0].PartId.ToString());
                        if (sysPart != null)
                        {
                            decimal _recqty = ifPurchaseDetailByPart[0].RecQty + decimal.Parse(num);// 预计实收数量（实收数量+当前条码的数量）用于判断原由的实收数量+当前扫描的条码数量是否大于应收数量
                            decimal revupperQty = 0;//收货上限比
                            decimal revdowmperQty = 0;//收货下限比

                            bool Issql = true;
                            if (sysPart.revdowmper > 0 && sysPart.revdowmper != null && sysPart.revupper > 0 && sysPart.revupper != null)
                            {
                                revupperQty = ifPurchaseDetailByPart[0].Qty * (1 + sysPart.revupper);//最多收多少
                                revdowmperQty = ifPurchaseDetailByPart[0].Qty * (1 - sysPart.revdowmper);//最少收多少
                                if (_recqty <= revupperQty)   //预计实收数量<=收货上限数量
                                {
                                    Issql = false;
                                }

                            }
                            else if (sysPart.revupper > 0 && sysPart.revupper != null)//收货上限比。实收数量可以大于应收数量
                            {
                                revupperQty = ifPurchaseDetailByPart[0].Qty * (1 + sysPart.revupper);
                                if (_recqty <= revupperQty)//预计实收数量<=收货上限数量
                                {
                                    Issql = false;
                                }

                            }
                            else if (sysPart.revdowmper > 0 && sysPart.revdowmper != null) //收货下限比。应收数量可以小于实收数量
                            {
                                revdowmperQty = ifPurchaseDetailByPart[0].Qty * (1 - sysPart.revdowmper);
                                if (_recqty <= ifPurchaseDetailByPart[0].Qty)// 预计实收数量  <= 应收数量
                                {
                                    Issql = false;
                                }

                            }
                            else //预计实收数量  <= 应收数量
                            {
                                if (_recqty <= ifPurchaseDetailByPart[0].Qty)//预计实收数量  <= 应收数量
                                {
                                    Issql = false;
                                }
                            }
                            if (Issql)
                            {
                                // 提示 " [M0090105] : 箱里的零件数量大于了应收数量!";
                                setDetail.type = "FAIL";
                                setDetail.message = " 箱里的零件数量大于了应收数量!";
                                setDetail.wmsObjectDetail = null;
                                return setDetail;
                            }


                        }


                        #region 修改采购明细表
                        //    StringBuilder updateString2 = new StringBuilder(1024);
                        ////本来修改的应收数量，现在改为实收数量
                        //updateString2.Append(@" update wms_purchase_detail set rec_qty= rec_qty + @rec_qty ,update_userid = @update_userid ,update_time =@update_time where  guid =@guid");

                        //DynamicParameters updateStringparameters2 = new DynamicParameters();
                        //updateStringparameters2.Add("@rec_qty", num);
                        //updateStringparameters2.Add("@update_userid", loginId);
                        //updateStringparameters2.Add("@update_time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        //updateStringparameters2.Add("@guid", ifPurchaseDetailByPart[0].Guid);
                        //insertStrings.Add(updateString2.ToString());
                        //insertparameterList.Add(updateStringparameters2);
                        #endregion

                    }
                    else 
                    {
						setDetail.type = "NO";
						setDetail.message = "零件号不符，请重新扫描！";
						setDetail.wmsObjectDetail = null;
						return setDetail;
					}
                    #endregion




                    //执行事务
                    IDbTransaction inserttransaction = dbConn.BeginTransaction();

					bool successCount = true;
					for (int i = 0; i < insertStrings.Count; i++)
					{
						if (dbConn.Execute(insertStrings[i], insertparameterList[i], inserttransaction) < 1)
						{
							successCount = false;
						}
					}

					if (successCount)
					{
						inserttransaction.Commit();
                        setDetail.type = "OK";
                        return setDetail;
                    }
					else
					{
						inserttransaction.Rollback();
						setDetail.type = "NO";
						setDetail.message = "操作失败，请重新尝试！";
						setDetail.wmsObjectDetail = null;
						return setDetail;
					}

					#endregion

					//receving = zgj_order;


				}


                /*
				StringBuilder updateString = new StringBuilder(1024);
				//                updateString.Append(@"select a.order_no,a.part_id,a.part_no,a.part_spec,b.qty,b.boxqty,isnull(c.recqty,0) recqty,isnull(c.recboxqty,0) recboxqty,a.enabled  from wms_purchase_detail as a 
				//left join (select part_id,sum(qty) qty,count(1) as boxQty from sys_stock where ref_order_no=@order_no and enabled='Y'  group by part_id ) as b on a.part_id = b.part_id
				//left join (select part_id,sum(qty) recQty,count(1) as recBoxQty from sys_stock where ref_order_no=@order_no and enabled='Y' and status not in (@status20,@status150) group by part_id ) as c on a.part_id=c.part_id
				//where a.order_no=@order_no and a.enabled='Y' order by cast( a.item_no as int)");、
				updateString.Append(@"select a.order_no,a.part_id,a.part_no,a.part_spec,a.qty,b.boxqty,isnull(c.recqty,0) recqty,isnull(c.recboxqty,0) recboxqty,isnull(d.pick_up_tab,0) pick_up_tab,a.enabled,e.instock_type AS IsDirectWarehousing  from wms_purchase_detail as a 
left join (select part_id,sum(qty) qty,count(1) as boxQty,IsDirectWarehousing from sys_stock where ref_order_no=@order_no and enabled='Y'  group by part_id,IsDirectWarehousing ) as b on a.part_id = b.part_id
left join (select part_id,sum(qty) recQty,count(1) as recBoxQty from sys_stock where ref_order_no=@order_no and enabled='Y' and status not in (@status20,@status150) group by part_id ) as c on a.part_id=c.part_id 
left join (select part_id,count(1) pick_up_tab from sys_stock where ref_order_no=@order_no and enabled='Y' and pick_up_tab='1' and status not in (@status20,@status150) group by part_id ) as d on  a.part_id=d.part_id 
LEFT JOIN dbo.sys_part e ON a.part_id=e.part_id 
 where a.order_no=@order_no and a.enabled='Y' AND e.enabled='Y'    order by cast( a.item_no as int) ");


				DynamicParameters updateStringparameters = new DynamicParameters();
				updateStringparameters.Add("@order_no", receving);
				updateStringparameters.Add("@status20", (int)WmsEnumUtil.StockStatus.WAITING_RECEIVE);
				updateStringparameters.Add("@status150", (int)WmsEnumUtil.StockStatus.REJECTION);
				//通过扫描箱条码，获取对应收货订单
				List<WmsPurchaseDetail> dt = dbConn.Query<WmsPurchaseDetail>(updateString.ToString(), updateStringparameters).ToList();

				if (dt.Count > 0)
				{
					if (receving.Length > 0)//有订单列表在执行中
					{
						//判断是否与当前收货中的订单一致
						List<WmsPurchaseDetail> Details = dt.Where(a => a.OrderNo == receving && a.Enabled == "Y").ToList();

						if (Details.Count > 0)
						{
							setDetail.type = "OK";
							setDetail.wmsObjectDetail = dt.ConvertAll(s => (object)s);
							return setDetail;
						}
						else
						{
							setDetail.type = "NO";
							setDetail.message = "[" + cartonNo + "]: 不在此送货单内!";
							setDetail.wmsObjectDetail = null;
							return setDetail;
						}
					}
					else
					{
						setDetail.type = "OK";
						setDetail.wmsObjectDetail = dt.ConvertAll(s => (object)s);
						return setDetail;
					}
				}
				else
				{
					//setDetail.type = "NO";
					//setDetail.message = "未查询到收货订单!";
					//setDetail.wmsObjectDetail = null;
					return setDetail;
				}
                */
                return null;
			}

		}

		/// <summary>
		/// 通过箱条码获取收货订单的明细信息  , 支给件没有信息就新增信息（后绑定新增方法）
		/// </summary>
		/// <param name="cartonNo"></param>
		/// <param name="receving"></param>
		/// <returns></returns>
		public SetObjectDetail GetPurchaseSummaryInfo(string cartonNo, string receving, string supportingParts, string loginId,string nstock)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				SetObjectDetail setDetail = new SetObjectDetail();
				string zgj_order = string.Empty;

                if (nstock == "Y")//第一次进入页面
                {
					StringBuilder _updateString = new StringBuilder(1024);
					_updateString.Append(@" SELECT b.order_no,a.part_id,a.part_no,a.part_spec,SUM(a.qty) qty, SUM(ISNULL(a.box_qty,0)) box_qty, SUM(isnull(a.rec_qty,0)) recqty,SUM(ISNULL(a.rec_box_qty,0)) recboxqty,
                                            a.enabled, c.instock_type AS IsDirectWarehousing  FROM wms_purchase_detail a LEFT JOIN dbo.wms_purchase b ON a.order_no=b.order_no LEFT JOIN dbo.sys_part c ON a.part_id=c.part_id
                        WHERE b.order_status in (10,30)  AND a.enabled='Y' AND b.enabled='Y' AND c.enabled='Y' AND a.order_no=@order_no
                    GROUP BY b.order_no,a.part_id,a.part_no,a.part_spec, a.qty,a.box_qty,a.rec_qty,a.rec_box_qty,a.enabled, c.instock_type ");


					DynamicParameters _updateStringparameters = new DynamicParameters();
					_updateStringparameters.Add("@order_no", receving);

					//通过扫描箱条码，获取对应收货订单
					List<WmsPurchaseDetail> _dt = dbConn.Query<WmsPurchaseDetail>(_updateString.ToString(), _updateStringparameters).ToList();
                    if (_dt.Count > 0)
                    {
						setDetail.type = "OK";
						setDetail.wmsObjectDetail = _dt.ConvertAll(s => (object)s);
						return setDetail;
					}

				}
                return null;

			}

		}

		public WmsPurchase GetRejectionByOrderNoInfo(string orderNo)
		{
			using (IDbConnection dbConn = dapperDbContext.GetDbConnection())
			{
				dbConn.Open();

				string strSql = " SELECT order_no,ref_order_no  FROM dbo.wms_purchase (nolock) where enabled = 'Y'AND order_no='"+ orderNo + "';";

				return dbConn.Query<WmsPurchase>(strSql).FirstOrDefault();

			}
		}


	}

}
